Sub topic 11
Chaining exceptions with raise from
This chapter assumes you can write try/except blocks, raise exceptions with raise, and define a simple exception class. It covers how to keep the original error attached when you raise a new one.
Why chain exceptions
Low-level code fails with low-level errors, such as a ValueError from int(). Callers of your function usually want a higher-level error that matches your API, such as ConfigError. If you raise the new error and discard the old one, you lose the detail that explains the real cause.
Chaining links the two exceptions. The traceback then shows both, and the new exception stores a reference to the original.
Implicit chaining
If a new exception is raised while an except block is handling another one, Python links them automatically. The original is stored in __context__.
try:
int("abc")
except ValueError:
raise KeyError("port")The traceback shows the ValueError, then this line:
During handling of the above exception, another exception occurred:
That wording suggests the second error may be an accident, such as a bug inside the handler. It does not say you meant to translate one error into another.
Explicit chaining with raise from
Use raise NewError(...) from original to say that the original is the direct cause. Python stores it in __cause__.
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__))This prints invalid port: 'abc', then the original ValueError. In an uncaught traceback, the connecting line reads:
The above exception was the direct cause of the following exception:
Suppressing the context with from None
Sometimes the original error is only noise. raise ... from None hides it from the traceback.
def get_setting(settings, name):
try:
return settings[name]
except KeyError:
raise LookupError(f"missing setting: {name}") from None
get_setting({}, "port")Python still records the original in __context__, but sets __suppress_context__ to True, so the traceback does not display it. Use this only when the original adds nothing for the reader.
The three attributes
| Attribute | Set when | Shown in traceback |
|---|---|---|
| `__context__` | A new exception is raised while handling another | Yes, unless suppressed |
| `__cause__` | You use `raise ... from original` | Yes, as the direct cause |
| `__suppress_context__` | You use `from` with any value, including `None` | Controls whether `__context__` is hidden |
Common errors
- Using
fromoutside anexceptblock. It works, but there is usually no original exception to link, so the chain adds nothing. - Forgetting
as exc. You need the name bound to writefrom exc. - Chaining with
from Noneby habit. This throws away debugging information. Keep the chain unless it misleads. - Putting a secret in the message. Chained tracebacks print every message in the chain, so check each one for passwords or tokens.
Exercise
A function catches KeyError and raises ConfigError("missing key") with no from. Which attribute of the ConfigError holds the KeyError, and what changes in the traceback if you add from exc?
Show answer
Without from, the KeyError is in __context__ and the traceback says "During handling of the above exception, another exception occurred". With from exc, it is also in __cause__ and the traceback says "The above exception was the direct cause of the following exception".
Exercise
What does raise ConfigError("bad") from None do to __cause__, __context__, and the traceback?
Show answer
__cause__ is None. __context__ still holds the original exception, but __suppress_context__ is True, so the traceback shows only the ConfigError.