Tejas Manohar Tejas Manohar - 1 month ago 7
Python Question

How to access re-raised exception in Python 3?

In Python 3, there's a useful

feature to re-raise an exception. That said, how do you find the original (/ re-raised) exception from the raised exception? Here's a (silly) example with comments to demonstrate what I mean--

def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except as err:
raise Exception("blah") from err

try:
some_func()
except as err:
# how can I access the original exception (TypeError)?

Answer

It's in the __cause__ attribute of the raised exception. Taken from the docs on the raise statement it says regarding raise ... from ...:

The from clause is used for exception chaining: if given, the second expression must be another exception class or instance, which will then be attached to the raised exception as the __cause__ attribute (which is writable). If the raised exception is not handled, both exceptions will be printed.

So, in your given scenario, repring the __cause__ attribute:

def some_func():
    try:
      None() # TypeError: 'NoneType' object is not callable
    except TypeError as err:
      raise Exception("blah") from err

try:
    some_func()
except Exception as er:
    print(repr(er.__cause__))

Will print out:

TypeError("'NoneType' object is not callable",)