jab
jab

Reputation: 4063

Python nested try/except - raise first exception?

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?

Upvotes: 4

Views: 3161

Answers (3)

Ethan Furman
Ethan Furman

Reputation: 69031

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 ... :

Upvotes: 0

user2555451
user2555451

Reputation:

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.

Upvotes: 3

justhalf
justhalf

Reputation: 9107

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.

Upvotes: 2

Related Questions