是否可以取消尚未被捕获的异常? [英] Is it possible to cancel an exception that has not been caught?

查看:151
本文介绍了是否可以取消尚未被捕获的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我想利用一个自定义的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中:你已经处理了他们抓住他们的地方,你不能从他们发生的地方继续下去。有关讨论,请参见此主题



编辑:根据您的评论,听起来好像您正在尝试捕获整个程序中的所有异常。您只想捕获某些对象上的未定义的属性查找。如果是这样,只需定义一个 __ getattr __


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.

这篇关于是否可以取消尚未被捕获的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆