exceptions within user-defined functions?

Bernard Yue bernie at 3captus.com
Thu Jun 12 23:41:21 EDT 2003


e y suzuki wrote:

>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
>  
>
NameError is raised before entering str2no() because before a function is
called, the python interpreter prepares the parameter(s).  Since 't' is 
undefined,
exception is raised while calling str2no(), but before any statement within
str2no() is executed.

Now lets look at str2no():

    def str2no(x):
       try:
           val=int(x)
           print val
       except (NameError,ValueError),msg:
           print msg

Sincec 'x' is passed in as a parameter.  'x' is always defined within 
the scope of
str2no(), henceNameError exception will never be raised within str2no().

>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
>
>
>  
>
Bernie
-- 

There are three schools of magic.  One:  State a tautology, then ring
the changes on its corollaries; that's philosophy.  Two:  Record many
facts.  Try to find a pattern.  Then make a wrong guess at the next
fact; that's science.  Three:  Be aware that you live in a malevolent
Universe controlled by Murphy's Law, sometimes offset by Brewster's
Factor; that's engineering.
                -- Robert A. Heinlein







More information about the Python-list mailing list