Learn Python
>>> exception_handling.exception_chaining

Exception Chaining in Python

#concept

Exception chaining preserves the full story when one exception leads to another — using raise NewException("...") from original_exception keeps a record of the original problem attached to the new one, rather than losing that context. It's especially useful when catching a low-level exception and re-raising it as something more meaningful to the caller, without hiding what actually triggered it underneath.

#how it works
1

Catch an exception as usual

Inside an except block, exactly as before.

2

Raise a new exception with from

raise NewException("...") from original_error links the two together.

3

The original becomes __cause__

Python attaches it to the new exception, and both appear in the traceback.

4

This beats a plain raise NewException(...)

Which would otherwise hide exactly what triggered the failure underneath.

5

Chaining also happens automatically

Without from, whenever a new exception is raised while already handling another one.

#example
def parse_age(text):
try:
return int(text)
except ValueError as e:
raise ValueError(f"Invalid age: {text!r}") from e
 
try:
parse_age("not a number")
except ValueError as e:
print(e)
print(e.__cause__)
Output
Invalid age: 'not a number'
invalid literal for int() with base 10: 'not a number'
1int("not a number") raises the original ValueError, caught by the inner except block.
2raise ValueError(...) from e creates a new, more descriptive exception, explicitly linking the original one as its cause.
3The outer except block catches the new exception, and e.__cause__ still gives access to the original underlying error, preserving the full chain of what actually happened.
#use cases
Turning a low-level, technical exception into a clearer, more specific one for the caller, without losing the original detail
Debugging a chain of failures by inspecting __cause__ to see exactly what triggered a higher-level error
Wrapping a third-party library's exceptions in a project's own exception types, while preserving the original for logging
Writing clearer tracebacks for anyone debugging code later, showing the true root cause instead of a dead end

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.