简体   繁体   中英

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?

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM