4

I'm trying to do a nested try/catch block in Python to print some extra debugging information:

try:
    assert( False )
except:
    print "some debugging information"
    try:
        another_function()
    except:
        print "that didn't work either"
    else:
        print "ooh, that worked!"
    raise

I'd like to always re-raise the first error, but this code appears to raise the second error (the one caught with "that didn't work either"). Is there a way to re-raise the first exception?

1
  • what are you trying to do ?
    – karthikr
    Oct 1, 2013 at 4:10

3 Answers 3

3

raise, with no arguments, raises the last exception. To get the behavior you want, put the error in a variable so that you can raise with that exception instead:

try:
    assert( False )
# Right here
except Exception as e:
    print "some debugging information"
    try:
        another_function()
    except:
        print "that didn't work either"
    else:
        print "ooh, that worked!"
    raise e

Note however that you should capture for a more specific exception rather than just Exception.

0
2

You should capture the first Exception in a variable.

try:
    assert(False)
except Exception as e:
    print "some debugging information"
    try:
        another_function()
    except:
        print "that didn't work either"
    else:
        print "ooh, that worked!"
    raise e

raise by default will raise the last Exception.

0

raise raises the last exception caught unless you specify otherwise. If you want to reraise an early exception, you have to bind it to a name for later reference.

In Python 2.x:

try:
    assert False
except Exception, e:
    ...
    raise e

In Python 3.x:

try:
    assert False
except Exception as e:
    ...
    raise e

Unless you are writing general purpose code, you want to catch only the exceptions you are prepared to deal with... so in the above example you would write:

except AssertionError ... :

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.