Why this script can work?

Diez B. Roggisch deets at nospam.web.de
Fri Jan 19 11:12:37 CET 2007


Jm lists wrote:

> Please help with this script:
> 
> class ShortInputException(Exception):
>         '''A user-defined exception class.'''
>         def __init__(self,length,atleast):
>                 Exception.__init__(self)
>                 self.length=length
>                 self.atleast=atleast
> 
> try:
>         s=raw_input('Enter something --> ')
>         if len(s)<3:
>                 raise ShortInputException(len(s),3)
>         # Other work can continue as usual here
> except EOFError:
>         print '\nWhy did you do an EOF on me?'
> except ShortInputException,x:
>         print 'ShortInputException: The input was of length %d, was
> expecting at least %d' %(x.length,x.atleast)
> else:
>         print 'No exception was raised.'
> 
> 
> My questions are:
> 
> 1) ShortInputException,x:   what's the 'x'? where is it coming?

except <ExceptionSpec>, <variable>:

will catch an exception of the kind specified in <ExceptionSpec> (it might
actually be more than one), and store the exception object in the variable
named <variable>

> 2) The 'if' and 'else' are not in the same indent scope,why this can work?


Because additionally to if, also for and try have else-clauses. The latter
two are only being called if the body of the control structure hasn't been
left due to "unnatural" circumstances. See this:




for i in xrange(10):
    pass
else:
    print "test 1"

for i in xrange(10):
    break
else:
    print "test 2"

try:
    pass
except:
    pass
else:
    print "test 3"

try:
    raise "I know I shouldn't rais strings..."
except:
    pass
else:
    print "test 4"



It will only print 

test 1
test 3


Diez



More information about the Python-list mailing list