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.
Python code
23 linesclass 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
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
- Use `dataclass` with inheritance or a simple `Exception` subclass for more fields.
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.