开发者

Python - How to catch outside exceptions inside methods

I want to know if there would开发者_如何学C be a way to catch exceptions inside called methods.

Example:

def foo(value):
    print value

foo(x)

This would throw a NameError exception, because x is not declared. I'd like to catch this NameError exception inside foo method. Is there a way?


The NameError occurs when x is attempted to be evaluated. foo is never entered, so you can't catch the NameError inside foo.

I think what you think is that when you do foo(x), foo is entered, and then x is looked up. You'd like to say, "I don't know what x is", instead of letting a NameError get raised.

Unfortunately (for what you want to do), Python, like pretty much every other programming language, evaluates its arguments before they are passed to the function. There's no way to stop the NameError of a value passed into foo from inside foo.


Not exactly, but there is a way to catch every exception that isn't handled:

>>> import sys
>>> 
>>> def handler(type, value, traceback):
>>>     print "Blocked:", value
>>> sys.excepthook = handler
>>> 
>>> def foo(value):
>>>     print value
>>> 
>>> foo(x)
Blocked: name 'x' is not defined

Unfortunately, sys.excepthook is only called "just before the program exits," so you can't return control to your program, much less insert the exception into foo().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜