Python嵌套try/except-引发第一个异常?
我尝试在Python中执行嵌套的try/catch块,以打印一些额外的调试信息:Python嵌套try/except-引发第一个异常?,python,try-catch,Python,Try Catch,我尝试在Python中执行嵌套的try/catch块,以打印一些额外的调试信息: try: assert( False ) except: print "some debugging information" try: another_function() except: print "that didn't work either" else: print "ooh, that worked!" r
try:
assert( False )
except:
print "some debugging information"
try:
another_function()
except:
print "that didn't work either"
else:
print "ooh, that worked!"
raise
我希望总是重新引发第一个错误,但这段代码似乎引发了第二个错误(被捕获为“那也不起作用”)。是否有方法重新引发第一个异常?您应该在变量中捕获第一个异常
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
将引发最后一个异常。raise
在没有参数的情况下引发最后一个异常。若要获得所需的行为,请将错误放入变量中,以便可以使用该异常引发:
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
但是请注意,您应该捕获更具体的异常,而不仅仅是
异常
引发
引发上次捕获的异常,除非您另有指定。如果要重新释放早期异常,则必须将其绑定到名称以供以后参考
在Python 2.x中:
try:
assert False
except Exception, e:
...
raise e
在Python 3.x中:
try:
assert False
except Exception as e:
...
raise e
除非您正在编写通用代码,否则您只希望捕获准备处理的异常。。。因此,在上面的示例中,您将编写:
except AssertionError ... :
你想干什么?