exceptions within user-defined functions?

Jiwon Seo jiwon at softwise.co.kr
Fri Jun 13 01:07:42 EDT 2003


e y suzuki <suzuki-python at pixar.com> wrote in message news:<mailman.1055470343.2955.python-list at python.org>...
> 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

Yes, you don't seem to understand when python evaluate variables.
Python uses applicative-order evaluation, which means python evaluates
argument first and then applies them. So, your function "str2no" never
sees 't' directly, but will see evaluated value. (because python tries
to evaluate before applying t to your function) But, since 't' is not
defined, it cannot be evaluated. Thus python interpreter gives you
Traceback "before" actaully calling your function.

try:
   str2no(t)
except (NameError),msg:
   print msg

if you do like above in the interpreter, it will print msg.

However, alternative evaluation model would be normal-order
evaluation, in which case, variables will not be evaluated until it is
actually used. If python used normal-order evaluation, you'd have got
what you wanted.




More information about the Python-list mailing list