Sub topic 7
Carrying data on an exception
Before you start
This chapter assumes you can write a class that subclasses Exception and raise and catch it. It also assumes you know what super().__init__ does. The earlier chapters covered both. The examples reuse a base class named AppError, which is the single root of the package's exception hierarchy.
Why put data on an exception
A bare exception class tells the caller what went wrong. It doesn't tell the caller the details. Suppose a withdrawal fails because the balance is too low. The message might say "Cannot withdraw 80; balance is 50". A handler that wants to show the user how much more money is needed has two options:
- Parse the message with a regular expression. This breaks when someone rewords the message or translates it.
- Read an attribute such as
exc.amount. This keeps working as long as the attribute exists.
An exception is an ordinary object, so you can store whatever data you like on it. The message is for people reading logs. The attributes are for code that handles the error.
A first version with a custom `__init__`
To accept extra arguments, define __init__. Store each value as an attribute. Then build a readable message and pass it 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}")
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"Short by {shortfall}")
print(exc)This prints:
Short by 30
Cannot withdraw 80; balance is 50The raise site supplies raw values. The class decides how to format them. If you later change the wording, no caller breaks, because callers use exc.amount and exc.balance.
What each line does
self.balance = balanceandself.amount = amountmake the data available to handlers.super().__init__(...)passes one string toException. That string becomesexc.args[0], andstr(exc)returns it. Tracebacks print it.- The class docstring says when the exception is raised, as the naming chapter recommended.
Keyword-only and optional data
Some data is not always known. An HTTP client error always has a status code, but only some responses carry a retry delay. Make required values keyword-only with *, and give optional values a default of None. Keyword-only parameters make the raise site self-describing.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ApiError(AppError):
"""Raised when a remote API returns an error response."""
def __init__(self, message, *, status_code, retry_after=None):
super().__init__(message)
self.status_code = status_code
self.retry_after = retry_after
def call_api():
raise ApiError("rate limited", status_code=429, retry_after=2.5)
try:
call_api()
except ApiError as exc:
if exc.status_code == 429 and exc.retry_after is not None:
print(f"retry in {exc.retry_after} seconds")
else:
raiseThis prints retry in 2.5 seconds. The bare raise in the else branch re-raises the same exception with its original traceback. That is the right move when the handler can't deal with the error.
A message argument is a good fit when the raise site knows something a template can't. Use a fixed template, as in InsufficientFundsError, when the message is fully determined by the data.
Extending a parent's attributes in a subclass
In a hierarchy, a subclass usually adds more data. Accept what the subclass needs, then call the parent's __init__ with what the parent needs.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ValidationError(AppError):
"""Raised when a field value is not acceptable."""
def __init__(self, field, reason):
super().__init__(f"{field}: {reason}")
self.field = field
self.reason = reason
class OutOfRangeError(ValidationError):
"""Raised when a numeric field is outside its allowed range."""
def __init__(self, field, value, minimum, maximum):
super().__init__(field, f"{value} not in [{minimum}, {maximum}]")
self.value = value
self.minimum = minimum
self.maximum = maximum
def validate_age(age):
if not 0 <= age <= 120:
raise OutOfRangeError("age", age, 0, 120)
problems = []
for age in (30, -5, 200):
try:
validate_age(age)
except ValidationError as exc:
problems.append((exc.field, exc.reason))
print(problems)The output is:
[('age', '-5 not in [0, 120]'), ('age', '200 not in [0, 120]')]The handler catches the general ValidationError and reads only the attributes every validation error has. A handler that cares about ranges can catch OutOfRangeError and read exc.minimum and exc.maximum. The subclass keeps everything the parent promises, so code written for the parent still works.
Choosing what to store
Not every value belongs on an exception. A useful rule: store what a handler needs to decide what to do, or what a log reader needs to diagnose the problem.
| Store this | Avoid this |
|---|---|
| Identifiers such as a field name, a user ID, or a file path | Large objects such as whole request bodies or database connections |
| Simple values such as numbers, strings, and enums | Secrets such as passwords, tokens, and API keys |
| A status code or a stable error code | Objects that can't be copied or pickled, such as open files, locks, and sockets |
| Copies of mutable data, if you need a snapshot | A reference to a list you keep modifying |
Three reasons drive this table.
- Lifetime. An exception's traceback holds references to every stack frame it passed through. A large attached object stays alive as long as the exception does.
- Leaks. Exception attributes often end up in logs and error trackers. Any secret you attach can be written out.
- Copying. Frameworks that run work in other processes need to send exceptions between them, which requires the data to survive pickling. Keep attributes simple so that stays possible.
Class attributes versus instance attributes
Some data is the same for every instance of an exception class. Put that data on the class. Put per-raise data on the instance.
class AppError(Exception):
"""Base class for errors raised by this application."""
code = "app_error"
class NotFoundError(AppError):
"""Raised when a requested resource does not exist."""
code = "not_found"
def __init__(self, resource, identifier):
super().__init__(f"{resource} {identifier!r} not found")
self.resource = resource
self.identifier = identifier
try:
raise NotFoundError("user", 42)
except AppError as exc:
print(exc.code, exc.resource, exc.identifier)This prints not_found user 42. A handler that catches only AppError can still read exc.code, because the base class defines a default. Class attributes cost nothing per instance and can be read without raising anything, as in NotFoundError.code.
Edge cases and gotchas
Forgetting `super().__init__`
BaseException fills args from the positional arguments passed to the constructor, before __init__ runs. If your __init__ never calls super().__init__, the message depends on how the caller wrote the call.
class AppError(Exception):
"""Base class for errors raised by this application."""
class Broken(AppError):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
print(repr(str(Broken(50, 80))))
print(repr(str(Broken(balance=50, amount=80))))
print(Broken(balance=50, amount=80).args)The three lines print '(50, 80)', then '', then (). With positional arguments, the message is the tuple of arguments, which is not what you wanted. With keyword arguments, args is empty and the traceback shows no message. Always call super().__init__ with a message.
Attribute names that already mean something
BaseException defines args, with_traceback, add_note, and the double-underscore attributes __cause__, __context__, __traceback__, and __notes__. Don't reuse these names for your own data. In particular, assigning to self.args changes what str(exc) and pickling see. A plain name like message is safe in Python 3, but it duplicates str(exc), so only add it if handlers need the text on its own.
Mutating attributes after raising
Handlers can read and change attributes, since they are ordinary instance attributes. That is occasionally useful, for example to record that a retry already happened. It also makes the exception a shared mutable object once it is re-raised or stored. Treat attributes as read-only by convention unless you have a specific reason.
Pickling
The classes in this chapter pass a formatted string to super().__init__, but their constructors take other arguments. When Python copies or unpickles such an exception, it calls the class with the contents of args, which here is a single string. That does not match __init__(self, balance, amount), so the rebuild fails. This matters when exceptions cross process boundaries, for example in multiprocessing or concurrent.futures. The chapters on args and __str__ and on pickling safety show how to keep args consistent with the constructor.
Summary of the pattern
- Define
__init__with the data the handler needs. Use keyword-only parameters for values that would be confusing by position. - Store each value as an instance attribute.
- Call
super().__init__with a readable message. - In subclasses, pass the parent's values up through
super().__init__and add your own attributes. - Put constant data, such as an error code, on the class.
Exercise
Write a class RateLimitError that subclasses AppError. It takes a required keyword-only limit (an int) and an optional keyword-only retry_after (default None). Its message should read "Rate limit of N exceeded". Then show a handler that prints the wait time when retry_after is set. Why call super().__init__ rather than only setting attributes?
Show answer
Code: class RateLimitError(AppError): """Raised when a caller exceeds the allowed request rate.""" def _init(self, *, limit, retryafter=None): super()._init(f"Rate limit of {limit} exceeded") self.limit = limit self.retryafter = retryafter try: raise RateLimitError(limit=100, retryafter=30) except RateLimitError as exc: if exc.retryafter is not None: print(f"wait {exc.retryafter} seconds") Calling super()._init_ with the message sets args and makes str(exc) and the traceback show the message. If you only set attributes, keyword-only construction leaves args empty and str(exc) returns an empty string.
Exercise
A teammate writes class FileError(AppError) with def __init__(self, path): self.path = path, and raises it as FileError(path="/tmp/x"). What does str(exc) return, and how would you fix the class?
Show answer
str(exc) returns an empty string, because the keyword argument is not stored in args and the base _init was never called. Fix it by calling super().init with a message, for example super().init_(f"Cannot process file: {path}"), and keep self.path = path so handlers can read the attribute.