前言
Exception类是常用的异常类,该类包括StandardError,StopIteration, GeneratorExit, Warning等异常类。python中的异常使用继承结构创建,可以在异常处理程序中捕获基类异常,也可以捕获各种子类异常,python中使用try...except语句捕获异常,异常子句定义在try子句后面。
Python中的异常处理
异常处理的语句结构
try: <statements> #运行try语句块,并试图捕获异常except <name1>: <statements> #如果name1异常发现,那么执行该语句块。except (name2, name3): <statements> #如果元组内的任意异常发生,那么捕获它except <name4> as <variable>: <statements> #如果name4异常发生,那么进入该语句块,并把异常实例命名为variableexcept: <statements> #发生了以上所有列出的异常之外的异常else:<statements> #如果没有异常发生,那么执行该语句块finally: <statement> #无论是否有异常发生,均会执行该语句块。
说明
else和finally是可选的,可能会有0个或多个except,但是,如果出现一个else的话,必须有至少一个except。raise语句
raise语句用来手动抛出一个异常,有下面几种调用格式:
raise #可以在raise语句之前创建该实例或者在raise语句中创建。 raise #Python会隐式地创建类的实例 raise name(value) #抛出异常的同时,提供额外信息value raise # 把最近一次产生的异常重新抛出来 raise exception from E例如:
抛出带有额外信息的ValueError: raise ValueError('we can only accept positive values')
当使用from的时候,第二个表达式指定了另一个异常类或实例,它会附加到引发异常的__cause__
属性。如果引发的异常没有捕获,Python把异常也作为标准出错消息的一部分打印出来:
比如下面的代码:
try: 1/0except Exception as E: raise TypeError('bad input') from E
执行的结果如下:
Traceback (most recent call last): File "hh.py", line 2, in <module> 1/0ZeroDivisionError: division by zeroThe above exception was the direct cause of the following exception:Traceback (most recent call last): File "hh.py", line 4, in <module> raise TypeError('bad input') from ETypeError: bad input
assert语句
assert主要用来做断言,通常用在单元测试中较多,到时候再做介绍。
with...as语句
with语句支持更丰富的基于对象的协议,可以为代码块定义支持进入和离开动作。
新闻热点
疑难解答