我正在编写一个捕获错误(或异常)的小脚本。但是当异常发生时,我想获得所有信息,如回溯、异常名称和异常消息。如果未捕获到异常但不应影响以下代码,它也应该采取行动(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
最佳答案
您需要使用回溯模块:
import traceback
try:
raise Exception('what')
except Exception:
print(traceback.format_exc())
关于python - 打印异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16257422/