2015-11-29 47 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")