问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/14993129/is-it-possible-to-cancel-an-exception-that-has-not-been-caught