【发布时间】:2013-04-27 22:16:06
【问题描述】:
我正在编写一个捕获错误(或异常)的小脚本。但是当异常发生时,我希望获得所有信息,例如 Traceback、异常名称和异常消息。如果未捕获异常但不影响以下代码(即应该出现错误但脚本不会停止工作),它也应该采取行动。
例如:在下面的代码中会抛出一个异常。如果发生这种情况(并且只有当它发生时)我想做“清理”。
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
【问题讨论】:
-
我假设你的意思是它应该“表现得好像没有发生异常”而不是被捕获......因为如果它没有被捕获,你会得到你的回溯打印你说对了吗?
-
不完全:如果没有出现异常(应该出现错误),它也应该起作用,但下面的代码一定不受它的影响。