Exception chaining
- Python course
- Intermediate
- Lesson 84/116
- 5 min
Learn exception chaining with raise ... from.
Chaining with raise ... from
When you catch an error you can convert it to another error type and raise: raise RuntimeError("...") from e. The from e part links the original error to the new error's __cause__ attribute; this preserves the error chain.
Chaining is used to wrap a low-level error into a high-level one without losing the original context. For example when you convert a database error to a RuntimeError, keeping the original DatabaseError as __cause__ makes debugging easier.
Chaining with nested try
Chaining is usually combined with nested try. The inner try catches a low-level error and raises a new one; the outer try catches this new error. This builds layered error handling.
For example a data conversion function may turn a ValueError into a RuntimeError and raise it; the caller only catches RuntimeError. It can reach the original ValueError through the __cause__ attribute; that way it can see the low-level reason.
Practice Raise RuntimeError with chaining
Write two nested try blocks. The outer try: block contains a second try: block. In the inner block call value = int("abc") and in except ValueError as e: write raise RuntimeError("Conversion error") from e. In the outer except RuntimeError as e: block print print(type(e).__name__) and print(type(e.__cause__).__name__).
Starter code
# Write nested try blocks
# Inner: convert ValueError to RuntimeError (with from e)
# Outer: catch RuntimeError, print type and cause typeSample solution
# Write nested try blocks
try:
# Inner: convert ValueError to RuntimeError (with from e)
try:
value = int("abc")
except ValueError as e:
raise RuntimeError("Conversion error") from e
# Outer: catch RuntimeError, print type and cause type
except RuntimeError as e:
print(type(e).__name__)
print(type(e.__cause__).__name__)Expected output
RuntimeError ValueError
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the chaining concepts
| Term | Meaning |
|---|---|
from |
Chaining keyword |
__cause__ |
Original error attribute |
raise |
Raise an error |
except |
Catch an error |
2 What does raise X from e do?
- Raises the new error without the old one
- Makes the new error a subclass of the old
- Sets the new error's __cause__ to e Correct answer
- Silences the old error
Explanation: That's how the chain is built.
3 Complete the from e clause
raise RuntimeError("Error") ____ e
raise RuntimeError("Error") from e
Explanation: The from e clause builds the chain.