Python nested try/except - raise first exception?

帅比萌擦擦* 提交于 2019-12-23 12:06:42

问题


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:


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.




回答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.




回答3:


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


来源:https://stackoverflow.com/questions/19107796/python-nested-try-except-raise-first-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!