1
我有一種情況,我想利用自定義sys.excepthook。當一個程序拋出一個異常時,sys.except鉤子被調用並執行一些操作。是否可以取消尚未被捕獲的異常?
例子:
import sys
def ehook(exctype, value, traceback):
t = 'Keys'
if exctype == AttributeError and value.args[0].split("'")[1] == t:
print "t %s" % (t,)
else:
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = ehook
class Keys():
@staticmethod
def x():
print "this is Keys.x()"
if __name__ == "__main__":
Keys.x()
Keys.noexist()
print "I want to continue here and beyond..."
有沒有一種方法,我可以取消在excepthook活動異常,因此不會導致程序退出?
你想處理所有異常,或'KeyError','AttributeError'等? – 2013-02-21 01:35:38
只是AttributeError。我試圖實現的是以某種方式允許用戶調用諸如Keys.group(),Keys.revert()等等,其中Keys方法group(),revert()未定義,但我可以捕獲那些未定義的方法名稱並使用它們返回使用這些名稱的內容。像return str(「keyname_」+ the_undefined_name「)。我想避免必須包裝在嘗試except子句。 – 2013-02-21 02:06:46
@DaveKierans:這聽起來像你正在尋找'__getattr__'。看到我編輯的答案 – BrenBarn 2013-02-21 02:10:30