Python nested try/except - raise first exception?
我正在尝试在Python中执行嵌套的try / catch块来打印一些额外的调试信息:
1 2 3 4 5 6 7 8 9 10 11 | try: assert( False ) except: print"some debugging information" try: another_function() except: print"that didn't work either" else: print"ooh, that worked!" raise |
我想总是重新提出第一个错误,但是这段代码似乎引发了第二个错误(那个"没有用"的错误)。 有没有办法重新提出第一个例外?
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
但请注意,您应捕获更具体的异常,而不仅仅是
您应该捕获变量中的第一个异常。
1 2 3 4 5 6 7 8 9 10 11 | 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 |
默认情况下,
除非另行指定,否则
在Python 2.x中:
1 2 3 4 5 | try: assert False except Exception, e: ... raise e |
在Python 3.x中:
1 2 3 4 5 | try: assert False except Exception as e: ... raise e |
除非您正在编写通用代码,否则您只想捕获您准备处理的异常...所以在上面的示例中,您将编写:
1 | except AssertionError ... : |