Sub topic 9
Preserving the cause with raise from
This chapter assumes you can write try/except blocks and define a subclass of Exception. It shows how to keep the original error attached when you raise your own exception.
Why the cause matters
Custom exceptions often translate a low-level failure into an application-level one. int("abc") raises ValueError, but your caller wants to know that the configuration is invalid. If you replace the error without keeping the original, you lose the details that help you debug: the exact value, the line, and the library that failed.
Python can keep both errors in one traceback. That is called exception chaining.
Raising with from
Use raise NewError(...) from original inside an except block:
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__)The from exc clause stores the ValueError in the new exception's __cause__ attribute. The program prints ValueError and then the original message. Callers that catch ConfigError can still inspect __cause__ when they need the details.
If the error is uncaught, the traceback shows both exceptions:
ValueError: invalid literal for int() with base 10: 'abc'
The above exception was the direct cause of the following exception:
ConfigError: invalid port: 'abc'The phrase "direct cause" tells the reader the translation was deliberate.
Implicit chaining
If you raise a new exception inside an except block without from, Python still links the two. It stores the original in __context__ and prints a different message: "During handling of the above exception, another exception occurred". That wording suggests something went wrong inside your error handler, which is usually not what you mean. Add from exc when the new exception is a deliberate translation.
The three forms
| Form | `__cause__` | `__context__` | Traceback shows |
|---|---|---|---|
| `raise New` | `None` | original | "During handling of the above exception..." |
| `raise New from exc` | original | original | "The above exception was the direct cause..." |
| `raise New from None` | `None` | original | only the new exception |
from None sets __suppress_context__ to True. The original is still stored in __context__, but the traceback does not print it.
When to hide the cause
Use from None only when the original error is an implementation detail that would confuse the reader. An example is a dictionary KeyError that you convert to a clear "unknown setting" error. Keep the cause whenever the low-level failure could help someone diagnose the problem.
Common mistakes
- Leaving out
from excwhen translating an error. The traceback then blames your handler instead of the real failure. - Using
from Noneby habit. This throws away the information you will want in production logs. - Catching
Exceptionand raising a new error that drops the original message text entirely. Even with chaining, include the bad value in your own message so the failure is understandable on its own. - Calling
str(exc)and putting it in the new message instead of chaining. You lose the original traceback and the exception type.
Checking the chain in a test
You can verify chaining in a test with pytest.raises, as shown in the testing chapter. Check info.value.__cause__ with isinstance. This catches regressions where someone later removes the from exc clause.
Exercise
A function catches a KeyError and raises ConfigError(f"unknown setting: {name}") with no from clause. What does the traceback say, and which attribute holds the KeyError?
Show answer
The traceback says "During handling of the above exception, another exception occurred". The KeyError is in _context, and cause is None. Adding "from exc" would set cause_ and change the traceback text to "The above exception was the direct cause of the following exception".