Python 自定义异常

这个自定义异常的案例里面,有个关键字没有做解释。

果断GOOGLE一下,raise的意思是抛出指定的异常。

其他的倒没什么,不过这种指定异常应该挺特殊的,但是没有想到该在什么场景使用。。

#!/usr/bin/python
#coding=gbk


#自定义一个异常
class ShortInputException(Exception):
    def __init__(self,length,atleast):
        Exception.__init__(self)
        self.length=length
        self.atleast=atleast

try:
    #这里主要是捕获输入
    s=raw_input('Enter the Context:')
    #如果长度小于三的情况下
    if len(s) < 3:
     #抛出一个自定义的异常
        raise ShortInputException(len(s),3)
except EOFError:
    print 'Error 01'
#这个就是自定义异常出现以后的处理方法
except ShortInputException,x:
    print 'The input was of length %d,was expection at least %d' % (x.length,x.atleast)
else:
    print 'No exception!'
原文地址:https://www.cnblogs.com/xiaoCon/p/2947928.html