Exception chaining enables users to see if an exception is the direct consequence of another exception (see PEP-3134). This is useful to propagate the original context of the error.
Exceptions are chained using either of the following syntax:
try:
...
except OSError as e:
raise RuntimeError("Something went wrong") from e
- With the
__cause__
property
try:
...
except OSError as e:
new_exception = RuntimeError("Something went wrong")
new_exception.__cause__ = e
raise new_exception
It is also possible to erase a chaining by setting new_exception.__cause__ = None
or using raise new_exception from None
(see PEP-409).
Chaining will fail and raise a TypeError
if something other than None
or a valid exception, i.e. an instance or a
subclass of BaseException
, is provided.