Python Exception Handling: try, except, else, finally
What you’ll learn
Section titled “What you’ll learn”- Using
try,except,else, andfinallyto handle errors gracefully. - Raising exceptions with
raiseand chaining them withraise ... from. - Defining custom exception classes for domain-specific errors.
- Avoiding the common mistake of swallowing exceptions with bare
except:.
Prerequisites
Section titled “Prerequisites”- Python 3.9+ installed
- Familiarity with functions and conditionals
What is an exception?
Section titled “What is an exception?”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.
Step 1 — Basic try/except
Section titled “Step 1 — Basic try/except”Save as exceptions.py and run with python exceptions.py (Python 3.9+):
try: result = 10 / 0except ZeroDivisionError: print("Cannot divide by zero")# Cannot divide by zeroStep 2 — Catching specific types
Section titled “Step 2 — Catching specific types”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.99print(parse_amount("abc")) # Cannot parse 'abc'... → 0.0Catch multiple types with a tuple:
try: result = risky_operation()except (ValueError, TypeError) as e: print(f"Input error: {e}")Step 3 — else and finally
Section titled “Step 3 — else and finally”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 completeelse: runs only if thetryblock 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.
Step 4 — Raising exceptions
Section titled “Step 4 — Raising exceptions”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.0apply_discount(100.0, 1.5) # ValueErrorRe-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 tracebackStep 5 — Exception chaining
Section titled “Step 5 — Exception chaining”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 unreachableThe traceback shows both the original and the re-raised exception, making debugging much easier.
Step 6 — Custom exception classes
Section titled “Step 6 — Custom exception classes”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 availableexcept 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.
Common mistakes
Section titled “Common mistakes”- Bare
except:orexcept Exception:. This silently swallows real bugs, includingKeyboardInterrupt, making problems much harder to diagnose. Catch only what you expect. - Empty
exceptblocks.except SomeError: passhides the error completely. At minimum, log it. - Using
raise einstead of bareraise.raise estarts a new traceback from the current line, losing the original context. Use bareraiseto preserve it. - Using exceptions for normal flow control. In hot loops,
if key in dis faster than catchingKeyError.
Next steps
Section titled “Next steps”- Error handling in depth — the full article from the main series
- raise from feature guide — exception chaining patterns
- File operations tutorial — using
withfor safe file handling
Official references
Section titled “Official references”- Python docs: Errors and Exceptions
- Python docs: Built-in Exceptions
- PEP 3134 — exception chaining