Printing an exception
我正在写一个捕获错误(或异常)的小脚本。但是当异常发生时,我希望拥有所有的信息,比如回溯、异常名称和异常消息。如果未捕获异常,但不应影响以下代码(应该出现I.D错误,但脚本不会停止工作),则也应该执行此操作。例如:在以下代码中,将引发异常。如果发生这种情况(而且只有发生这种情况),我想做"清理"。
1 2 3 4 5 6 7 8 9 10 11 | try: 1 / 0 except Exception as e: # Printing the Exception like it would have been done if the exception hadn't been caught: # Traceback (most recent call last): # File"<stdin>", line 1, in <module> # ZeroDivisionError: integer division or modulo by zero # With the traceback, the exception name and the exception message. # Doing some additional stuff. pass |
我不打算使用记录器,因为脚本非常智能(不超过100行),它将只由我使用。
编辑:我使用的是python2.x
您将要使用回溯模块:
1 2 3 4 5 | import traceback try: raise Exception('what') except Exception: print(traceback.format_exc()) |
你可以解决:
It should also act if the exception hadn't been caught.
具有
1 2 3 4 5 | try: 1 / 0 except Exception as e: do_cleanup(e) raise |