🐍 Python Advanced

What is Python's chained exceptions?

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.