我正在编写一个捕获错误(或异常)的小脚本.但是当异常发生时,我希望获得所有信息,如Traceback,异常名称和异常消息.如果没有捕获到异常但是下面的代码不应该受到影响它也应该起作用(i.d应该出现错误,但脚本不会停止工作).
例如:在以下代码中将抛出异常.如果发生这种情况(并且只有它发生)我想做“清理”.
例如:在以下代码中将抛出异常.如果发生这种情况(并且只有它发生)我想做“清理”.
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行)并且它只会被我使用.
编辑:我正在使用python 2.x.
解决方法
您将要使用traceback模块:
import traceback try: raise Exception('what') except Exception: print(traceback.format_exc())