+ -
当前位置:首页 → 问答吧 → python3.1 异常处理语法问题

python3.1 异常处理语法问题

时间:2010-12-13

来源:互联网

《Python简明教程》里的例子:
Python code
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast
try:
    s = 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.')



为什么总是提示:
except ShortInputException, x: 这句语法错误?
试了半天,不知道怎么写,一般怎么查语法呢?多谢了。

作者: taiyangniao   发布时间: 2010-12-13

if len(s) < 3:
  raise ShortInputException(len(s), 3)
这句话说明你输入的时候要输入一个长度为3的字符串,如'555','abc'

作者: bh20077   发布时间: 2010-12-13

自己查查手册吧。你那语法是2版的吧,3版的估计得except ShortInputException as x:

作者: angel_su   发布时间: 2010-12-13

2.x的这个语法是挺sb的,一直很不爽。

作者: iambic   发布时间: 2010-12-13