Is there a standard way of using exception chains in Python 3?


During the handling of one exception ‘A’, it is possible that another exception ‘B’ may occur. In Python 2.0 versions, if this happens, exception B is propagated outward and exception A is lost. It is useful to know about both exceptions in order to debug the problem.

Sometimes it is useful for an exception handler to deliberately re-raise an exception, either to provide extra information or to translate an exception to another type. The __cause__ attribute provides an explicit way to record the direct cause of an exception.

Exception chaining is only available in Python 3.  Python 3 has the raise ... from clause to chain exceptions. We rewrite given code using raise..from clause as follows

try:
s = {‘a’:1, ‘b’:2}['c']
except KeyError as e:
raise ValueError('failed') from e

Python 3 will by default show all exceptions that occurred during exception handling, like this:

Traceback (most recent call last):
File "source_file.py", line 2, in <module>
s = {'a':1, ‘b’:2}['c']
KeyError: 'c'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "source_file.py", line 4, in <module>
raise ValueError('failed') from e
ValueError: failed

Updated on: 27-Sep-2019

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements