How to Raise a Custom Exception with Extra Context in Python

Define a custom exception that carries extra context fields and raise it to provide richer error information.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

23 lines
Python 3.9+
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Withdrawal of ${amount} failed: balance ${balance} is insufficient")


def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount


def main():
    try:
        withdraw(100, 150)
    except InsufficientFundsError as e:
        print(f"Error: {e}")
        print(f"Context — balance: {e.balance}, amount: {e.amount}")


if __name__ == "__main__":
    main()

Output

stdout
Error: Withdrawal of $150 failed: balance $100 is insufficient
Context — balance: 100, amount: 150

How it works

By subclassing Exception, you create a custom exception type that behaves like any other exception. The __init__ method stores extra context attributes (balance and amount) before calling super().__init__ with a formatted message. This lets the exception carry both a human-readable message and structured data that a handler can inspect programmatically. Catching the specific subclass allows clean, targeted error handling without masking unrelated bugs.

Common mistakes

  • Forgetting to call `super().__init__` which leaves the message empty.
  • Overriding `__str__` instead of passing a message to `super().__init__`.
  • Catching the base `Exception` in the handler instead of the specific subclass.

Variations

  1. Use `dataclass` with inheritance or a simple `Exception` subclass for more fields.
  2. Raise the exception with keyword arguments for clearer call sites.

Real-world use cases

  • Banking or payment systems where insufficient funds errors need the current balance for user feedback.
  • API input validation errors that carry which field was invalid to return precise error responses.
  • Order processing code that includes the missing item IDs in the exception for tracing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.