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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

nice, but py3 only. anyways: +1.
ah, nice. so according to that PEP, the answer is, "you can't, in Py2, but you can in Py3". thanks!
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.

1 Comment

That just swallows the "in the try" exception before it gets to the finally block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.