python__基础 : 异常处理与自定义异常

异常处理方法一般为:

try:
    ------code-----

except Exception as e: # 抛出异常之后将会执行
    print(e)

else:  # 没有异常将会执行
    print('no Exception')

finally:  # 有没有异常都会执行
    print('execute is finish')

可以用 raise 抛出一个异常,以下是一个输入字符太短的异常例子:

class ShortInputException(Exception):
    '''自定义异常类'''
    def __init__(self, length, atleast):
        self.length = length
        self.atleast = atleast

try:
    s = input('please input:')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
except ShortInputException as e:
    print('输入长度是%s,长度至少是%s' %(e.length, e.atleast))
else:
    print('nothing...')

如果输入字符长度小于3,那么将会抛出 ShortInputException 异常:

>>> please input:qw
    输入长度是2,长度至少是3 

注意 如果异常处理时 再次 使用 raise 后面什么都没有,那么代表把这个异常还给系统,让解释器用默认的方式处理它.

猜你喜欢

转载自www.cnblogs.com/cccy0/p/9048723.html
今日推荐