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

Can I know the actual exception caught by the method?

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?

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 :

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