Exceptions
An exception is an object that interrupts normal control flow when something goes wrong. You raise one with raise and handle it with try / except / else / finally.
Detailed Explanation
Python uses exceptions for errors and for some non-error signals (StopIteration, GeneratorExit). When a problem occurs, the interpreter creates an exception object and starts unwinding the stack. Each frame is given a chance to handle it. If nobody does, the program prints a traceback and exits.
try marks a block you are willing to recover from. except ValueError: catches that class and its subclasses. More than one except is tried in order; the first match wins. A bare except: catches BaseException, including KeyboardInterrupt and SystemExit, and is almost always a mistake. Write except Exception: if you truly mean "any error", and then re-raise or log.
else on try runs when no exception was raised. It is the place for code that should not be covered by the except. finally always runs: on success, on a caught error, on a re-raise, on return. Use it for cleanup that is not already a context manager.
raise ValueError("cents must be positive") creates and throws. raise alone inside an except re-raises the current exception and keeps the original traceback. raise NewError(...) from exc chains the cause, which is what you want when you wrap a low-level error in a domain error. from None hides the cause, which you should do only when the original error is noise.
The exception type is the category; the message is the detail. Catch types, not messages. Catch the narrowest type you can handle. except Exception at the top of a request handler is a reasonable last resort so one bad request does not kill a server. except Exception around a single int() call is how you hide a real bug.
Exceptions are classes. You can define class OutOfStock(Exception): and raise it. Built-in types you will see often: ValueError (right type, wrong value), TypeError (wrong type), KeyError, IndexError, FileNotFoundError, TimeoutError. OSError is the parent of most I/O errors.
Tracebacks are the product. Keep them. Logging str(exc) without the traceback throws away the only information that locates the fault.
Code Examples
def parse_cents(raw: str) -> int:
try:
cents = int(raw)
except ValueError as exc:
raise ValueError(f"not an integer: {raw!r}") from exc
if cents < 0:
raise ValueError("cents must be >= 0")
return cents
print(parse_cents("2500")) # 2500path = "missing-config.json"
try:
text = open(path).read()
except FileNotFoundError:
text = "{}"
else:
print("loaded", path)
finally:
print("lookup finished")
print(text)class OutOfStock(Exception):
"""The requested SKU has no remaining units."""
def reserve(sku: str, stock: dict[str, int]) -> None:
if stock.get(sku, 0) <= 0:
raise OutOfStock(sku)
stock[sku] -= 1Common Gotchas
Catching too wide hides bugs
`except Exception` around four lines of business logic will also catch `NameError` and `TypeError` from your own mistakes.
`raise NewError()` inside `except` loses the cause
use `raise NewError(...) from exc` so the traceback shows both.
`finally` runs before `return`
a `return` in `finally` replaces a `return` in `try`. Do not return from `finally`.