Sub topic 9
Preserving the cause with raise from
This chapter assumes you can write try/except blocks, define a subclass of Exception, and call super().__init__. It also assumes you have seen the AppError and ConfigError classes from earlier chapters. You will learn how Python links one exception to another, how raise ... from controls that link, and when to hide the link on purpose.
Why the original error matters
A custom exception usually describes a problem in your application's terms: "invalid port" instead of "invalid literal for int()". That translation helps callers. It also destroys information if you throw the original error away. The original error often holds the detail you need during debugging: the bad value, the failing line, or the library that raised it.
Python solves this with exception chaining. Every exception object can point to another exception that led to it. The pointer is stored in one of two attributes, and raise ... from decides which one is used.
Implicit chaining with `__context__`
If you raise a new exception while handling another one, Python records the first exception in the new one's __context__ attribute. You do not have to do anything.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError:
raise ConfigError(f"invalid port: {raw!r}")
try:
load_port("abc")
except ConfigError as err:
print(type(err.__context__).__name__)
print(err.__cause__)This prints ValueError and then None. The ValueError is attached as context, but __cause__ is empty. The traceback shows both errors, joined by this sentence:
During handling of the above exception, another exception occurred:That wording suggests an accident, as if the error handler itself failed. In this code the new exception is deliberate, so the message is misleading to a reader.
Explicit chaining with `raise ... from`
Writing raise NewError(...) from original sets __cause__ to original. It also sets a flag, __suppress_context__, to True. The traceback then uses a different sentence:
The above exception was the direct cause of the following exception:Here is the chapter's main pattern, with a check of the attributes it sets:
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or 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(type(err.__cause__).__name__)
print(err.__cause__)
print(err.__suppress_context__)The output is:
ValueError
invalid literal for int() with base 10: 'abc'
TrueA full traceback prints the lower-level error first, then the sentence about the direct cause, then the application-level error. A reader sees what failed and why your code reported it as it did.
Choosing between the three forms
There are three ways to raise inside an except block. They differ in what ends up on the new exception.
| Statement | `__cause__` | `__context__` | `__suppress_context__` | Traceback shows |
|---|---|---|---|---|
| `raise New()` | `None` | the handled exception | `False` | "During handling..." |
| `raise New() from exc` | `exc` | the handled exception | `True` | "direct cause" |
| `raise New() from None` | `None` | the handled exception | `True` | only the new exception |
Notice that __context__ is filled in even for from None. Python still records it. The flag only tells the traceback printer to skip it. Code that walks __context__ directly can still reach the hidden error.
When `from None` is appropriate
Sometimes the original error is an implementation detail. Suppose a settings lookup uses a dictionary, and your public API should not mention KeyError:
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
SETTINGS = {"host": "localhost"}
def get_setting(name):
try:
return SETTINGS[name]
except KeyError:
raise ConfigError(f"missing setting {name!r}") from None
try:
get_setting("database_url")
except ConfigError as err:
print(err)
print(err.__cause__)
print(type(err.__context__).__name__)This prints the message, then None, then KeyError. The traceback for an uncaught ConfigError shows one clean error.
Use from None rarely. The KeyError here carries no information that the new message lacks. If the original error could help someone debug, for example an OSError with an errno or a library exception with a response body, keep it with from exc.
What `from` accepts
The expression after from must be an exception instance, an exception class, or None. If you give a class, Python calls it with no arguments to create an instance. Anything else raises TypeError.
You can also chain outside an except block. This is useful when you collect an error earlier and raise a summary later:
class AppError(Exception):
"""Base class for errors raised by this application."""
class BatchError(AppError):
"""Raised when a batch run fails."""
def run_batch(items):
first_failure = None
for item in items:
try:
int(item)
except ValueError as exc:
first_failure = exc
break
if first_failure is not None:
raise BatchError("batch stopped early") from first_failure
try:
run_batch(["1", "2", "x", "4"])
except BatchError as err:
print(repr(err.__cause__))Because from sets __cause__ directly, the chain is correct even though the original handler has finished.
Reading a whole chain in code
Logging tools such as logger.exception and traceback.print_exc already print the full chain. If you need to inspect it yourself, follow the same rule the traceback printer uses. Prefer __cause__. Fall back to __context__ only when it has not been suppressed.
def iter_chain(exc):
"""Yield exc and every exception that led to it, newest first."""
seen = set()
while exc is not None and id(exc) not in seen:
seen.add(id(exc))
yield exc
if exc.__cause__ is not None:
exc = exc.__cause__
elif not exc.__suppress_context__:
exc = exc.__context__
else:
exc = None
def parse(raw):
try:
return int(raw)
except ValueError as exc:
raise RuntimeError("parse failed") from exc
try:
parse("abc")
except RuntimeError as err:
for item in iter_chain(err):
print(type(item).__name__)This prints RuntimeError and then ValueError. The seen set guards against a cycle. Cycles are rare, but nothing in the language prevents one, and a loop that never ends inside an error handler is a bad failure to debug.
Testing the cause
A test that only checks the type of the raised exception cannot tell whether you preserved the original error. Check __cause__ explicitly:
import pytest
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from exc
def test_load_port_rejects_text():
with pytest.raises(ConfigError, match="invalid port") as info:
load_port("abc")
assert isinstance(info.value.__cause__, ValueError)info.value is the exception object that pytest.raises caught. If someone later removes from exc, __cause__ becomes None and this test fails. For a from None case, assert that __cause__ is None and __suppress_context__ is True.
Common mistakes
- Raising a new exception with no
fromwhen you meant to translate. The error still works, but the traceback says "During handling", which implies a bug in the handler. - Catching, logging, and raising a fresh exception with no link. If you raise outside the
exceptblock, no context is recorded at all, and the original error is lost. - Wrapping at every layer. If each of five functions wraps the error in its own exception type, the chain grows long and the useful message sits at the bottom. Translate once, at a boundary where the vocabulary changes, such as from
ValueErrortoConfigError. - Putting the original message into the new one by hand. Writing
f"failed: {exc}"duplicates text that the chain already shows. Describe what your code was trying to do, and let__cause__explain why it failed. - Using
fromwith a value that is not an exception.raise ConfigError("x") from "reason"raisesTypeError, notConfigError.
Summary of the working model
Every exception has __context__ (set automatically when raised during handling), __cause__ (set by from), and __suppress_context__ (set by from, including from None). The traceback shows the cause if there is one, or else the context unless it is suppressed. Use from exc for deliberate translation, from None for hiding a pure implementation detail, and a plain raise only when the second failure is truly separate.
Exercise
A function reads a user's age from a string. It catches ValueError and raises a custom ValidationError (a subclass of AppError). The traceback currently says "During handling of the above exception, another exception occurred". What one-line change makes it say "The above exception was the direct cause of the following exception", and which attribute of the ValidationError instance would a test check to confirm the change?
Show answer
Change raise ValidationError(...) to raise ValidationError(...) from exc, where exc is bound with except ValueError as exc. A test would check info.value.__cause__, for example assert isinstance(info.value.__cause__, ValueError).
Exercise
Given raise ConfigError("missing") from None inside an except KeyError block, what are the values of __cause__, __context__, and __suppress_context__ on the raised exception?
Show answer
__cause__ is None, __context__ is the KeyError that was being handled, and __suppress_context__ is True. The traceback hides the KeyError, but it is still reachable through __context__.