Python Try-Except inside of Function
Solution 1
This has nothing to do with your exception handler. The error you are seeing is because "foo" is not defined anywhere.
Solution 2
The name error is happening before it ever gets into tryAppend. It evaluates the value of foo when trying to pass it to the function. This works:
def tryAppend(child, parent):
parent.append(child)
var1 = []
try:
tryAppend(foo, var1)
except NameError:
print 'WRONG NAME'
Solution 3
The NameError is being thrown when the name 'foo' is evaluated, which is before entering the function. Therefore the try/except within the function isn't relevant.
Solution 4
For someone who is looking for how to use try except construction inside of the function. I am not sure whether it is a good programming style, but it works.
You can put string arguments to the function. It will be evaluated correctly and then you can use exec
inside of the function:
def tryAppend(child, parent):
try:
script = parent + '.append(' + child + ')'
exec script
return parent
except NameError:
print "WRONG NAME"
var1 = []
var2 = 'test2'
tryAppend('var2', 'var1')
tryAppend('foo', 'var1')
garen
Updated on January 30, 2022Comments
-
garen over 2 years
I've got a pretty good understanding of python's try-except clause, but I'm encountering problems when trying to put it inside of a function.
>>> def tryAppend(child, parent): ... try: ... parent.append(child) ... except NameError: ... print "WRONG NAME" >>> var1 = [] >>> var2 = 'test2' >>> tryAppend(var2, var1) #works, no error >>> tryAppend(foo, var1) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'foo' is not defined
it is almost like python doesn't see the try: statement. Any help is appreciated.