我正在写一个捕捉错误(或例外)的小脚本。但是,当发生异常时,我想拥有所有信息,如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的
蟒蛇2.x的..... – Matt3o12 2013-04-27 22:18:13
使用谷歌.. http://stackoverflow.com/questions/3702675/print-the-full-traceback-in-python -without-halting-the-program – Gricha 2013-04-27 22:19:27
我假设你的意思是它应该“表现得好像异常没有被提出”而不是被捕获......因为如果它没有被捕获,你会得到你的回溯对吗? – underrun 2013-04-27 22:21:31