Sub topic 7
Carrying data on an exception
This chapter assumes you can write classes and use super().__init__(). It also assumes you know try, except, and raise, and that you have a package base class like the AppError from the earlier chapters. The next chapter covers how args and __str__ behave. Here the goal is to attach data to an exception so callers can use it.
Why attach data
A message is written for a person reading a log. Code that catches the exception often needs the values behind the message, such as how much money was missing or which field failed validation.
If the values exist only inside the message string, the caller must parse text like "Cannot withdraw 80; balance is 50". That breaks when someone rewords the message. Storing the values as attributes gives callers a stable interface.
Storing attributes in `__init__`
Define __init__ with the data you need. Save each value on self, then pass a readable message to the base class.
class AppError(Exception):
"""Base class for errors raised by this application."""
class InsufficientFundsError(AppError):
"""Raised when a withdrawal exceeds the available balance."""
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {amount}; balance is {balance}")
try:
raise InsufficientFundsError(balance=50, amount=80)
except InsufficientFundsError as exc:
print(exc)
print(exc.amount - exc.balance)This prints Cannot withdraw 80; balance is 50 and then 30. The handler computed the shortfall from the attributes and never touched the message text.
The exception now has two jobs. The message goes to people, and the attributes go to code.
Making some data optional
Not every raise site knows every detail. Use default values for the pieces that may be missing, and keep the required ones positional.
class ValidationError(AppError):
"""Raised when a field value fails validation."""
def __init__(self, field, value=None, reason="invalid value"):
self.field = field
self.value = value
self.reason = reason
super().__init__(f"{field}: {reason} (got {value!r})")
try:
raise ValidationError("age", -3, reason="must be non-negative")
except ValidationError as exc:
print(exc.field, exc.reason)Callers can then write ValidationError("email") when they have nothing else to report, and the message still reads sensibly.
Guidelines for attributes
- Store plain, stable values such as numbers, strings, and identifiers. Avoid large objects like open connections, which keep resources alive as long as the exception is referenced.
- Name attributes after what they mean (
balance,field), not after their position. - Do not overwrite built-in exception attributes such as
args,with_traceback, or__cause__. - Build the message from the same values you store, so the two cannot disagree.
- Keep the constructor small. If you need many fields, the exception may be doing the work of a separate data class.
Reading the data in a handler
Attributes let a handler make decisions instead of just reporting a failure.
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
try:
withdraw(50, 80)
except InsufficientFundsError as exc:
shortfall = exc.amount - exc.balance
print(f"Please deposit at least {shortfall} first.")The handler turns the data into a user-facing action without any string handling.
Exercise
Write a MissingFieldError that subclasses AppError. Its __init__ takes record_id and field, stores both as attributes, and passes the message "Record 7 is missing 'email'" (with the actual values) to the base class. What does exc.field return after raise MissingFieldError(7, "email") is caught?
Show answer
Define __init__(self, record_id, field). Set self.record_id = record_id and self.field = field. Then call super().__init__(f"Record {record_id} is missing {field!r}"). After the exception is caught, exc.field returns 'email', and str(exc) returns "Record 7 is missing 'email'".