views:

101

answers:

2

I want to know if there would 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?

+8  A: 

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.

Mark Rushakoff
Sorry, I changed that. That's cause I wrote the method name 'method', but then changed the name.
Gabriel L. Oliveira
@Gabriel: It doesn't make a difference. `x` is still evaluated before the method is entered. You could do `argument = x; foo(argument)` which would be nearly equivalent, but of course the `NameError` would just be raised sooner, although still outside of the method.
Mark Rushakoff
+1  A: 

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().

eswald
Yes, it's not exactly that, but I'll try to figure out something with this. Thank you.
Gabriel L. Oliveira