python简明教程学习笔记 异常

    当我们的程序出现例外情况时就会发生异常(Exception)。当这种情况发生时,python将给出一个 Error。例如你把“print”写成了“Print”。

1.处理异常

    我们可以通过 try...except 来处理异常状况,我们以一个处理输入异常的作为举例。

    try:
        text = input('Enter your name --> ')
    except EOFError:
        print('Why did you do an EOF on me?')
    except KeyboardInterrupt:
        print('You cancelled the operation.')
    else:
        print('You entered {}'.format(text))

    要记住,每一个 try 的后面都需跟着 except ,它会验证出现的异常是否在预先设定好的范围之内。

2.抛出异常

    我们可以通过 raise 语句来引发一次异常,具体方法是提供错误名或异常名以及要抛出(Thrown) 异常的对象。在例子中,我们自己设定了一个继承于 Exception 类的异常类 ShortInputException 它将告诉我们出现异常的具体情况。

class ShortInputException(Exception):
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    text = input('Enter your name -->')
    if(len(text) < 3):
        raise ShortInputException(len(text), 3)
except EOFError:
    print('Why did you do an EOF on me?')
except ShortInputException as ex:
    print(('ShortInputException: The input was ' +
           '{0} long, expected at least {1}')
          .format(ex.length, ex.atleast))
else:
    print('No exception was raised.')

    在这里中,异常的抛出由 raise 引导,将文本信息传递给 ShortInputException 类。在 except 中我们使用 as(为),将 ShortInputException 储存为 ex。也就是说,当文本信息小于三个字符时,异类将会被抛出,从而引起 except ShortInputException as ex 的反应,进入到异常处理之中。

3.try...finally

    假设你正在你的读取中读取一份文件。你应该如何确保文件对象被正确关闭,无论是否会发生异常?这可以通过 finally 块来完成。在有 finally 情况下,就算发生异常,也将会执行 finally 语句后的命令。

f = None
try:
    f = open("poem.txt")
except IOError:
    print("Could not find file poem.txt")
except KeyboardInterrupt:
    print("!! You cancelled the reading from the file.")
finally:
    if f:
        f.close()
    print("(Cleaning up: Closed the file)")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值