Sub topic 11
Chaining exceptions with raise from
This chapter assumes you can write try/except blocks, raise exceptions with raise, and read a basic traceback. It also assumes you know how exception classes inherit from one another. You will learn how Python links one exception to another, how raise ... from ... controls that link, and when to hide the original error.
Why chaining exists
Low-level code fails in low-level terms. A ValueError from int() or a KeyError from a dictionary says little about what your program was trying to do. A common fix is to catch the low-level error and raise a higher-level one, such as ConfigError("invalid port").
If you do that carelessly, you lose the original cause. The person debugging sees only your new message. Chaining keeps both errors and records how they relate.
Python tracks two separate links on every exception object:
| Attribute | Set by | Meaning |
|---|---|---|
| `__cause__` | `raise X from Y` | Y is the direct, deliberate cause of X |
| `__context__` | Python, automatically | Y was being handled when X was raised |
| `__suppress_context__` | `raise X from Y` (including `from None`) | If true, the traceback hides `__context__` |
Implicit chaining
If a new exception is raised while an except block is running, Python stores the exception being handled in the new exception's __context__. You do not write anything extra.
def read_port(raw):
try:
return int(raw)
except ValueError:
raise RuntimeError("could not read port")
try:
read_port("abc")
except RuntimeError as err:
print(repr(err))
print(repr(err.__context__))
print(err.__cause__)The output is:
RuntimeError('could not read port')
ValueError("invalid literal for int() with base 10: 'abc'")
None__context__ holds the ValueError, and __cause__ is None because nothing declared a cause. When this goes uncaught, the traceback prints both errors, separated by this sentence:
During handling of the above exception, another exception occurred:That wording says "these happened together", not "this one caused that one". It is also what you see when your handler has a bug of its own, such as a typo that raises NameError inside the except block. In that case the message is accurate, and you want to see both errors.
Explicit chaining with raise from
When the new exception is a deliberate translation of the old one, say so with from:
class ConfigError(Exception):
"""Raised when configuration is invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
try:
load_port("abc")
except ConfigError as err:
print(err)
print(repr(err.__cause__))
print(err.__suppress_context__)Here __cause__ is the ValueError, and __suppress_context__ is True. An uncaught ConfigError now prints the traceback with a different connecting sentence:
The above exception was the direct cause of the following exception:The difference matters to readers of the traceback. "Direct cause" tells them the first error is the real reason. "During handling" tells them the two may be unrelated.
The expression after from must be an exception instance, an exception class (which Python instantiates), or None. Anything else raises TypeError.
Suppressing the context with from None
Sometimes the original error is noise. Suppose you look up a key in a dictionary to turn it into a friendlier error:
COLORS = {"red": "#ff0000", "green": "#00ff00"}
def color_hex(name):
try:
return COLORS[name]
except KeyError:
raise ValueError(f"unknown color: {name!r}") from None
try:
color_hex("blue")
except ValueError as err:
print(err)
print(err.__cause__)
print(err.__suppress_context__)
print(repr(err.__context__))from None sets __cause__ to None and __suppress_context__ to True. The traceback shows only the ValueError. Notice that __context__ is still filled in. Suppression only affects what the traceback prints. A debugger or logging code can still read the original through __context__.
Use from None only when the original exception adds nothing, as with KeyError above, where the new message already contains the key. If the original carries information you would want in a bug report, use from exc instead.
Choosing between the three forms
| Situation | Form | Traceback shows |
|---|---|---|
| Translating a low-level error into your own type | `raise New(...) from exc` | Both, labeled "direct cause" |
| The original is an implementation detail with no value | `raise New(...) from None` | Only the new exception |
| A handler fails on its own | plain `raise New(...)` | Both, labeled "during handling" |
Most translation code should use from exc. Inside an except block, plain raise New(...) is rarely what you want, because it makes a deliberate translation look like an accident.
Seeing the chain
The traceback walks the chain from the oldest exception to the newest. You can walk it yourself with a loop. This is useful in logging code that prints every layer of the failure.
def chain(exc):
"""Yield exc, then each exception that led to it."""
seen = set()
while exc is not None and id(exc) not in seen:
seen.add(id(exc))
yield exc
exc = exc.__cause__ or exc.__context__
class ConfigError(Exception):
pass
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
try:
load_port("abc")
except ConfigError as err:
for item in chain(err):
print(type(item).__name__, "-", item)The seen set guards against cycles. Python avoids creating cycles when it sets __context__ automatically, but you can build one by hand, so a defensive loop is cheap insurance.
The standard logging module does this for you. logger.exception(...) and logger.error(..., exc_info=True) format the full chain, including the "direct cause" and "during handling" lines.
Adding information without replacing the exception
If you only want to add a hint, you often do not need a new exception type. Since Python 3.11, add_note attaches a string to an existing exception. The notes print under the traceback.
def parse_line(number, line):
try:
return int(line)
except ValueError as exc:
exc.add_note(f"while parsing line {number}")
raise
try:
parse_line(7, "x")
except ValueError as err:
print(err.__notes__)This keeps the original type, so callers that already catch ValueError keep working. Compare that with translation: wrapping in ConfigError changes the type that callers must catch. Choose translation when the type is part of your interface. Choose a note when you only want to explain.
Common mistakes
- Chaining outside an except block.
raise New() from excworks anywhereexcis in scope, but the name bound byas excis deleted when theexceptblock ends. Save a reference first if you need it later. - Using
from Noneto hide your own bug. If a handler might fail for reasons you did not expect, suppressing the context hides the evidence. - Wrapping too much. Converting every exception into one generic type forces callers to inspect
__cause__to learn what happened. Translate at a clear boundary, such as the public function of a module. - Losing the traceback with a new exception when a re-raise would do. If you only want to log and pass the error on, use a bare
raiseinstead of creating a new exception. - Raising a class and expecting arguments.
raise ConfigError from excworks and creates the instance with no arguments. The message will be empty unless the class supplies one.
Reading a chained traceback
Read a chained traceback from the top. The first block is the earliest exception, which is usually the root cause. The last block is the exception that reached you. Fix the root cause when it is a bug in your code, and fix the translation when the new message is misleading.
Exercise
A function catches KeyError from a dictionary lookup and raises LookupFailed("no such user"). The caller's log shows the traceback line "During handling of the above exception, another exception occurred". Which change makes the log say the KeyError was the direct cause, and what would you write if the KeyError added no useful information?
Show answer
Add from exc after binding the original with except KeyError as exc:, so the line becomes raise LookupFailed("no such user") from exc. The traceback then reads "The above exception was the direct cause of the following exception". If the KeyError is just noise, write raise LookupFailed("no such user") from None, which hides the context in the traceback while leaving __context__ available to code.
Exercise
After raise B() from None inside an except block that was handling exception A, what are the values of B.__cause__, B.__suppress_context__, and B.__context__?
Show answer
__cause__ is None, __suppress_context__ is True, and __context__ is still A. Only the traceback display is suppressed.