← Back to Python, page 2

python-0029 · Easy fresher

How do you define a custom exception and raise it with useful context?

Subclass Exception (or a more specific built-in), optionally add attributes, and raise it with a clear message. Use raise NewError(...) from err to chain the original cause, which keeps the full traceback for debugging. Catch your own exception type at the boundary where you can handle it.

Full answer
python
class InsufficientStock(Exception):
    def __init__(self, item, wanted, available):
        super().__init__(f"{item}: wanted {wanted}, only {available} left")
        self.item, self.wanted, self.available = item, wanted, available

def reserve(stock, item, qty):
    try:
        available = stock[item]
    except KeyError as err:
        raise LookupError(f"unknown item {item!r}") from err
    if qty > available:
        raise InsufficientStock(item, qty, available)
    stock[item] -= qty

stock = {"pen": 2}
for item, qty in [("pen", 5), ("lamp", 1)]:
    try:
        reserve(stock, item, qty)
    except InsufficientStock as e:
        print("handled:", e, "| available =", e.available)
    except LookupError as e:
        print("handled:", e, "| cause:", type(e.__cause__).__name__)

Output:

text
handled: pen: wanted 5, only 2 left | available = 2
handled: unknown item 'lamp' | cause: KeyError

InsufficientStock carries structured data, so callers can react to e.available instead of parsing the message. For an unknown item, the KeyError is translated into a LookupError with a clearer message, and from err stores the original in __cause__, so a traceback would show both. Name exceptions after the problem, keep a small hierarchy for a library (one base class plus specific subclasses), and avoid catching broad Exception unless you re-raise or log it.

python
class InsufficientStock(Exception):
    def __init__(self, item, wanted, available):
        super().__init__(f"{item}: wanted {wanted}, only {available} left")
        self.item, self.wanted, self.available = item, wanted, available

def reserve(stock, item, qty):
    try:
        available = stock[item]
    except KeyError as err:
        raise LookupError(f"unknown item {item!r}") from err
    if qty > available:
        raise InsufficientStock(item, qty, available)
    stock[item] -= qty

stock = {"pen": 2}
for item, qty in [("pen", 5), ("lamp", 1)]:
    try:
        reserve(stock, item, qty)
    except InsufficientStock as e:
        print("handled:", e, "| available =", e.available)
    except LookupError as e:
        print("handled:", e, "| cause:", type(e.__cause__).__name__)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Subclass Exception
  • Add attributes for structured data
  • raise ... from keeps the cause
  • Catch specific types where you can handle them
  • One base class per library

Common mistakes

  • Raising bare Exception with a string
  • Swallowing the original error

Follow-ups

  • What does raise ... from None do?
  • How do exception notes (add_note) help?

Tips

  • Show __cause__