Try Except in python:语法issu

2024-09-30 10:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

我不明白这行的语法:except ShortInputException, x:

x在这里是为了什么?? 为什么它是一个物体???在

这条线有什么用?:Exception.__init__(self)

谢谢


Tags: selfinputleninitdefexceptionlengthclass
2条回答

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

ShortInputException(Exception)将您的类ShortInputException声明为Exception的子类。Exception.__init__(self)调用父类的构造函数。在

except ShortInputException, x:

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是引发的异常对象。在

except ShortInputException, x:

捕获类ShortInputException的异常,并将异常对象的实例绑定到x

更常见的语法是

^{pr2}$

PEP3110所述,这是首选。除非需要支持python2.5,否则应该使用as版本。在


Exception.__init__(self)

调用超级类的构造函数,该类是此用户定义类派生的类。在

相关问题 更多 >

    热门问题