Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Determine cause of exception

In this example

try:
    raise ValueError
except ValueError as e:
    raise IndexError from e

The traceback notes

...
ValueError:

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

IndexError
...

If I were to catch the IndexError, how would I inspect the traceback to discover that it was caused by a ValueError?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

According to PEP 3134, raise ... from sets the __cause__ attribute in the exception. You can access that:

try:
    try:
        raise ValueError
    except ValueError as e:
        raise IndexError from e
except IndexError as ee:
    print(type(ee.__cause__))

Result:

<class 'ValueError'>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading