简体   繁体   中英

Try Except in python :syntax issue

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)


except ShortInputException, x:
           print 'ShortInputException: The input was of length %d, \
           was expecting at least %d' % (x.length, x.atleast)

I dont understand the syntax of this line: except ShortInputException, x:

what is x here for ?? and why is it acting as an object ???

waht does this line do ? : Exception.__init__(self)

Thanks

except ShortInputException, x:

catches an exception of class ShortInputException and binds the instance of the exception object to x.

The more common syntax for this is

except ShortInputException as x

which is to be preferred as described in PEP3110 . Unless you need to support Python 2.5, you should use the as version.


Exception.__init__(self)

calls the constructor for the super class, the class that this user defined class derives from.

waht does this line do ? : Exception.__init__(self)

ShortInputException(Exception) declares your class ShortInputException as sub class of Exception . Exception.__init__(self) calls the constructor of parent class.

except ShortInputException, x:

From the doc :

When an exception occurs, it may have an associated value, also known as the exception's argument. The presence and type of the argument depend on the exception type.

The except clause may specify a variable after the exception name (or tuple). The variable is bound to an exception instance with the arguments stored in instance.args.

x in your example is the exception object raised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM