Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

The following code throws more than one exceptions

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

How to rewrite it to show exception chaining in python 3.x?


1 Answer
Rajendra Dharmkar

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



Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.