2013-04-27 96 views
2

我正在写一个捕捉错误(或例外)的小脚本。但是,当发生异常时,我想拥有所有信息,如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的

+0

蟒蛇2.x的..... – Matt3o12 2013-04-27 22:18:13

+0

使用谷歌.. http://stackoverflow.com/questions/3702675/print-the-full-traceback-in-python -without-halting-the-program – Gricha 2013-04-27 22:19:27

+0

我假设你的意思是它应该“表现得好像异常没有被提出”而不是被捕获......因为如果它没有被捕获,你会得到你的回溯对吗? – underrun 2013-04-27 22:21:31

回答

5

你要使用的追踪模块:

import traceback 
try: 
    raise Exception('what') 
except Exception: 
    print(traceback.format_exc()) 
0

可以解决:

还应该采取行动,如果该例外尚未被捕获。

try: 
    1/0 
except Exception as e: 
    do_cleanup(e) 
    raise 
+0

以下代码不应受该例外的影响。 – Matt3o12 2013-04-27 22:20:21

+2

所以你的意思是_“如果异常未被__激活__,它也应该起作用。他们非常不同。 – Eric 2013-04-27 22:20:52

+0

编辑:不正确:如果没有发生异常(应该出现错误),它也应该起作用,但下面的代码不得受其影响。 – Matt3o12 2013-04-27 22:21:34