Home > Software design >  Determine cause of exception
Determine cause of exception

Time:09-29

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?

CodePudding user response:

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