Home > Mobile >  Can I know the actual exception caught by the method?
Can I know the actual exception caught by the method?

Time:08-04

I have a scenario where I call a library method that catches any exception that occurs and re-throws another exception. Is there a way I can get the original exception? Please find a minimal reproducible code below:

def f():
    raise KeyError("key not found")

def g():
    try:
        f()
    except Exception as e:
        raise Exception(f'{e}')
    
try:
    g()
except KeyError:   # Does not work
    print('excepted')

Can I get that KeyError exception occurred?

CodePudding user response:

When you raise an exception in an except clause, the new exception's __context__ attribute is set to the original exception.

try:
    g()
except Exception as e:
    print(type(e.__context__))
    print(e.__context__)

outputs

<class 'KeyError'>
'key not found'
  • Related