码迷,mamicode.com
首页 > 编程语言 > 详细

Python:自定义异常类

时间:2015-06-16 21:20:19      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:python   异常   

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

#!/usr/bin/python
#Filename:user_defined_exception.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 = raw_input('Enter something-->')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
    else:
        print s
except 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.'


Python:自定义异常类

标签:python   异常   

原文地址:http://blog.csdn.net/nyist327/article/details/46521997

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!