问题描述
我有一种情况,我想利用一个自定义的sys.excepthook。当一个程序引发一个异常时,sys.except钩子被调用并且做了一些东西。示例:
import sys
def ehook(exctype,value,traceback):
t ='keys'
如果exctype == AttributeError和value.args [0]。 split(')[1] == t:
printt%s%(t,)
else:
sys .__ excepthook __(exctype,value,traceback)
sys.excepthook = ehook
class Keys():
@staticmethod
def x():
打印这是Keys.x()
如果__name__ ==__main__:
Keys.x()
Keys.noexist()
打印我想继续这里和以后...
有没有办法可以取消异常中的活动异常,因此不会导致程序退出?
否。在调用 sys.excepthook
之前,该异常已经在顶层被忽略,程序将在 sys.excepthook
做它的工作。 (请参见)。一般情况下,异常不可恢复在Python中:你已经处理了他们抓住他们的地方,你不能从他们发生的地方继续下去。有关讨论,请参见。
编辑:根据您的评论,听起来好像您正在尝试捕获整个程序中的所有异常。您只想捕获某些对象上的未定义的属性查找。如果是这样,只需定义一个。
I have a situation where I want to utilise a custom sys.excepthook. When a program throws an exception the sys.except hook gets called and does some stuff.
Example:
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..."
Is there a way I can cancel the active exception in the excepthook so it does not cause the program to exit?
No. By the time sys.excepthook
is called, the exception is already uncaught at the top level and the program will exit after sys.excepthook
does its work. (See the documentation.) In general exceptions aren't resumable in Python: you have handle them where you catch them, you can't just continue from where they happened. See this thread for a bit of discussion.
Edit: Based on your comment, it doesn't sound like you're trying to catch all exceptions in your whole program. You just want to catch undefined attribute lookups on certain objects. If that's the case, just define a __getattr__
on your class.
这篇关于是否可以取消尚未被捕获的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!