Why this script can work?

Robert Kern robert.kern at gmail.com
Fri Jan 19 01:57:58 EST 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?

It's the actual ShortInputException instance that was raised. Try printing
x.length and x.atleast, for example.

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

This else: clause goes with the try: and except: clauses, not the if: clause. It
is executed if no exception was raised.

  http://docs.python.org/ref/try.html

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list