exceptions within user-defined functions?
e y suzuki
suzuki-python at pixar.com
Thu Jun 12 22:11:05 EDT 2003
i'm trying to put together a try/except clause within a function. the
clause will specifically except the ValueError and NameError exceptions.
the clause can be put together fine, but i'm having a bit of trouble
making the NameError exception be caught when the clause is included in
a user-defined function.
try/except clause directly at the python interpreter appears fine for
both NameError and ValueError:
>>> try:
... val=int('eep')
... print val
... except (NameError,ValueError),msg:
... print msg
...
invalid literal for int(): eep
>>> try:
... val=int(t)
... print val
... except (NameError,ValueError),msg:
... print msg
...
name 't' is not defined
i now place the try/except clause in a function:
>>> def str2no(x):
... try:
... val=int(x)
... print val
... except (NameError,ValueError),msg:
... print msg
...
it appears to work fine for the ValueError, but although the traceback
for string t as input acknowledges that the error is a NameError, the
error isn't caught (even though it is excepted in the function above):
>>> str2no('eep')
invalid literal for int(): eep
>>> str2no(t)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 't' is not defined
i've also tried defining the str2no function without the ValueError
exception to isolate the NameError, to no avail. similar unsuccessful
result when excepting the parent error, StandardError, in lieu of both
ValueError and NameError (ValueError is caught fine).
what am i doing wrong? please advise.
thanks in advance,
-eys
More information about the Python-list
mailing list