Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: recover exception from try block if finally block raises exception

Say I have some code like this:

try:
    try:
        raise Exception("in the try")
    finally:
        raise Exception("in the finally")
except Exception, e:
    print "try block failed: %s" % (e,)

The output is:

try block failed: in the finally

From the point of that print statement, is there any way to access the exception raised in the try, or has it disappeared forever?

NOTE: I don't have a use case in mind; this is just curiosity.

like image 410
Claudiu Avatar asked Apr 20 '12 14:04

Claudiu


1 Answers

I can't find any information about whether this has been backported and don't have a Py2 installation handy, but in Python 3, e has an attribute called e.__context__, so that:

try:
    try:
        raise Exception("in the try")
    finally:
        raise Exception("in the finally")
except Exception as e:
    print(repr(e.__context__))

gives:

Exception('in the try',)

According to PEP 3314, before __context__ was added, information about the original exception was unavailable.

like image 93
lvc Avatar answered Oct 02 '22 16:10

lvc