Python:自定义异常类

来源:互联网 发布:苏曼莎捏脸数据 编辑:程序博客网 时间:2024/06/08 18:36

自定义一个异常类,判断用户输入的字符串长度是否够

#!/usr/bin/python#Filename:user_defined_exception.pyclass ShortInputException(Exception):    '''A user-defined exception class.'''    def __init__(self, length, atleast):        Exception.__init__(self)        self.length = length        self.atleast = atleasttry:    s = raw_input('Enter something-->')    if len(s) < 3:        raise ShortInputException(len(s), 3)    else:        print sexcept EOFError:    print '\nWhy did you do an EOF on me?'#except ShortInputException, x:except ShortInputException as x:    print 'ShortInputException:The input was length %d, \            was expecting at least %d.'%(x.length, x.atleast)else:    print 'No exception was raised.'


0 0
原创粉丝点击