Exception Handling
Exception Chaining
Preserving exception context with raise from
Interview: Advanced error handling — tests understanding of __cause__, __context__, and exception wrapping
Exception chaining lets you wrap a low-level exception in a higher-level one while preserving the original cause. This is essential for debugging — the traceback shows both the original error and the wrapping exception. Python supports explicit chaining with raise ... from and implicit chaining (automatic when raising inside except).
Types of Chaining
- Explicit:
raise NewError(...) from original_error— sets__cause__ - Implicit: Raising inside except block — sets
__context__ - Suppressed:
raise NewError(...) from None— hides the chain
Interview Tip
Know when to use each chaining type: from e for intentional wrapping, bare raise for implicit, from None to replace (e.g., converting implementation details to user-friendly errors).
Use Cases
Wrapping low-level errors (network, DB) in domain-specific exceptions
Converting implementation details to user-friendly error messages
Logging original errors while raising higher-level ones
Library design: exposing clean exceptions while preserving debugging info
Suppressing noisy chains with from None for cleaner tracebacks
Common Mistakes
Using raise e instead of raise ... from e (loses proper chaining)
Not using from None when intentionally replacing an exception
Chaining too many exceptions making tracebacks hard to read
Forgetting that __cause__ is explicit chaining, __context__ is implicit
Raising a new exception inside except without any chaining