🐍 Python Advanced

What is Python's chained exceptions?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

Answer

Python 3 supports exception chaining — when an exception is raised inside an except block, both exceptions are reported. Implicit chaining: raising a new exception in an except block automatically chains it: try: int("abc"); except ValueError as e: raise RuntimeError("Conversion failed") from e — the original ValueError is the __cause__. Explicit chaining: raise New() from old_exc — makes the cause explicit. Suppress chaining: raise New() from None — hides the original exception context. Access: exc.__cause__ (explicit), exc.__context__ (implicit). In tracebacks, Python shows the full chain: "During handling of the above exception, another exception occurred." This is invaluable for debugging — you see both the original problem and the secondary failure. Use raise New() from original when wrapping low-level exceptions in higher-level abstractions.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.