Skip to content

Python Exception Handling: try, except, else, finally

  • Using try, except, else, and finally to handle errors gracefully.
  • Raising exceptions with raise and chaining them with raise ... from.
  • Defining custom exception classes for domain-specific errors.
  • Avoiding the common mistake of swallowing exceptions with bare except:.
  • Python 3.9+ installed
  • Familiarity with functions and conditionals

Exceptions are Python’s mechanism for signaling and handling errors at runtime. When something unexpected happens, code raises an exception. If nothing catches it, the program terminates with a traceback. If you catch it, you decide what to do: log it, retry, return a fallback, or re-raise with more context.

Save as exceptions.py and run with python exceptions.py (Python 3.9+):

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Cannot divide by zero

Always catch the most specific exception type possible. Avoid bare except: which catches everything including bugs and system signals.

def parse_amount(raw: str) -> float:
try:
return float(raw)
except ValueError:
print(f"Cannot parse {raw!r} as a number, defaulting to 0.0")
return 0.0
print(parse_amount("149.99")) # 149.99
print(parse_amount("abc")) # Cannot parse 'abc'... → 0.0

Catch multiple types with a tuple:

try:
result = risky_operation()
except (ValueError, TypeError) as e:
print(f"Input error: {e}")
import json
def read_config(path: str) -> dict:
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
except FileNotFoundError:
print(f"Config not found, using defaults")
return {}
except json.JSONDecodeError as e:
print(f"Malformed JSON: {e}")
return {}
else:
# Runs only if no exception was raised in try
print(f"Loaded {len(data)} config keys")
return data
finally:
# Runs always — exception or not
print("Config load complete")
config = read_config("config.json")
# Config not found, using defaults
# Config load complete
  • else: runs only if the try block succeeded. Put success-path code here so it cannot accidentally catch exceptions it was not meant to handle.
  • finally: runs unconditionally. Use it for cleanup — closing files, releasing locks, resetting state.
def apply_discount(amount: float, pct: float) -> float:
if not 0.0 < pct <= 1.0:
raise ValueError(f"Discount must be between 0 and 1, got {pct}")
return round(amount * (1 - pct), 2)
print(apply_discount(100.0, 0.10)) # 90.0
apply_discount(100.0, 1.5) # ValueError

Re-raise the current exception with bare raise to preserve the original traceback:

try:
result = apply_discount(-10.0, 0.10)
except ValueError:
print("Caught error, logging...")
raise # re-raises with original traceback

When you catch one exception and raise a different one, use raise ... from to preserve the chain:

def fetch_order(order_id: str) -> dict:
raise ConnectionError("Database unreachable")
def get_order(order_id: str) -> dict:
try:
return fetch_order(order_id)
except ConnectionError as e:
raise RuntimeError(f"Cannot retrieve order {order_id!r}") from e
try:
get_order("ORD-001")
except RuntimeError as e:
print(e) # Cannot retrieve order 'ORD-001'
print(e.__cause__) # Database unreachable

The traceback shows both the original and the re-raised exception, making debugging much easier.

Define custom exceptions for domain-specific errors so callers can catch exactly what they need:

class OrdersPortalError(Exception):
"""Base class for all OrdersPortal exceptions."""
class OrderNotFoundError(OrdersPortalError):
def __init__(self, order_id: str) -> None:
self.order_id = order_id
super().__init__(f"Order {order_id!r} not found")
class InsufficientStockError(OrdersPortalError):
def __init__(self, sku: str, requested: int, available: int) -> None:
self.sku = sku
self.requested = requested
self.available = available
super().__init__(
f"Cannot fulfill {requested} units of {sku!r}: only {available} available"
)
def place_order(order_id: str, sku: str, qty: int) -> None:
stock = {"WIDGET-01": 5}
if sku not in stock:
raise OrderNotFoundError(order_id)
if stock[sku] < qty:
raise InsufficientStockError(sku, qty, stock[sku])
print(f"Order {order_id} placed: {qty} × {sku}")
try:
place_order("ORD-010", "WIDGET-01", 10)
except InsufficientStockError as e:
print(e) # Cannot fulfill 10 units of 'WIDGET-01': only 5 available
except OrdersPortalError as e:
print(f"Domain error: {e}")

The base OrdersPortalError class lets callers catch all domain errors with one except clause while still handling specific subtypes separately.

  • Bare except: or except Exception:. This silently swallows real bugs, including KeyboardInterrupt, making problems much harder to diagnose. Catch only what you expect.
  • Empty except blocks. except SomeError: pass hides the error completely. At minimum, log it.
  • Using raise e instead of bare raise. raise e starts a new traceback from the current line, losing the original context. Use bare raise to preserve it.
  • Using exceptions for normal flow control. In hot loops, if key in d is faster than catching KeyError.