Determine cause of exception

Advertisements

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?

>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'>

Leave a ReplyCancel reply