2015-11-29 89 views
2

编辑:在阅读评论和答案后,我意识到我想做的事情没有多大意义。我脑子里想的是,我 在我的代码一些地方可能会失败(通常是一些requests 通话可能不走,虽然),我想追上他们,而不是 把一个try:无处不在。我的具体问题是,我会 不在乎,如果他们失败,并不会影响其他代码 (说,看门狗的呼叫)。如何捕获所有未捕获的异常并继续?

我将离开这个问题供后人的颂歌“想想 真正的问题,再提问”

我试图处理所有未捕获的(否则未处理的)异常:

import traceback 
import sys 

def handle_exception(*exc_info): 
    print("--------------") 
    print(traceback.format_exception(*exc_info)) 
    print("--------------") 

sys.excepthook = handle_exception 
raise ValueError("something bad happened, but we got that covered") 
print("still there") 

此输出

-------------- 
['Traceback (most recent call last):\n', ' File "C:/Users/yop/.PyCharm50/config/scratches/scratch_40", line 10, in <module>\n raise ValueError("something bad happened, but we got that covered")\n', 'ValueError: something bad happened, but we got that covered\n'] 
-------------- 

所以,虽然加薪确实抓住了,它没有按照我的想法工作:致电handle_exception,然后用print("still there")继续。

我该怎么做?

+2

你不能,这不是一个明智的做法 - 如果有什么不好的事情意味着你的变量没有设置?你应该运行下一行,现在是'NameError's? – Eric

+0

你想要做一些像https://github.com/ajalt/fuckitpy – jonrsharpe

+0

@jonrsharpe:经过一些实际的思考 - 是的,我想是的。我会用那个想法更新我的问题。 – WoJ

回答

3

你不能这样做,因为Python会自动调用sys.excepthookfor uncaught exceptions

在交互式会话中,这发生在控制返回提示之前;在一个Python程序中,这个就在程序退出之前发生。

无法恢复执行程序或“禁止”sys.excepthook中的例外。

我能想到的最接近的是

try: 
    raise ValueError("something bad happened, but we got that covered") 
finally: 
    print("still there") 

有没有except条款,因此ValueError不会被抓到,但finally块保证会执行。因此,异常钩仍将被称为并'still there'将被打印,但finally子句将被执行之前sys.excepthook

如果在任何条款发生异常而没有被处理,则 例外暂时保存。 finally子句被执行。如果 存在保存的异常,则在finally 子句末尾重新生成该异常。

(从here

+0

*没有办法恢复程序的执行或“压缩”sys.excepthook中的异常*。 – WoJ

0

你后:

import traceback 
import sys 

try: 
    raise ValueError("something bad happened, but we got that covered") 
except Exception: 
    print("--------------") 
    print(traceback.format_exception(sys.exc_info())) 
    print("--------------") 
print("still there")