异常处理方法一般为:

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 后面什么都没有,那么代表把这个异常还给系统,让解释器用默认的方式处理它.

相关文章:

  • 2022-01-10
  • 2021-05-03
  • 2021-05-07
  • 2021-06-22
  • 2021-07-15
  • 2021-09-29
  • 2022-12-23
  • 2021-10-03
猜你喜欢
  • 2021-09-10
  • 2021-07-21
  • 2021-06-13
  • 2021-10-11
  • 2022-02-10
  • 2022-12-23
  • 2021-10-16
相关资源
相似解决方案