14

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.

Claudiu
  • 224,032
  • 165
  • 485
  • 680

2 Answers2

14

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.

lvc
  • 34,233
  • 10
  • 73
  • 98
0
try:
    try:
        raise Exception("in the try")
    except Exception, e:
        print "try block failed"
    finally:
        raise Exception("in the finally")
except Exception, e:
    print "finally block failed: %s" % (e,)

However, It would be a good idea to avoid having code that is likely to throw an exception in the finally block - usually you just use it to do cleanup etc. anyway.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636