暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

python异常之raise语句

原创 梯阅线条 2024-01-03
287

1 python异常之raise语句

python通过raise语句显式触发异常,raise后面跟类名或实例名。

1.1 基本用法

用法

raise <类名> raise <实例名> raise

描述

(1) raise <类名>,则python自动调用类的不带参数的构造函数,来触发异常;

(2) raise <实例名>,触发指定实例名的异常;

(3) raise ,重新触发当前异常,通常用于异常处理器中,传递已经捕获的异常;

示例

>>> try: raise TypeError except TypeError: print('raise重新引发当前异常') raise raise重新引发当前异常 Traceback (most recent call last): File "<pyshell#10>", line 2, in <module> raise TypeError TypeError

1.2 raise from

raise from 用于描述当前异常与except捕获异常的关系。

用法

raise [异常[('异常说明')]] raise 异常 from 变量 raise 异常 from None

描述

在except分句编写raise时,用于向外传递异常,如果不接参数,则传递except捕获的异常,如果接参数,则传递最新的异常,并且说明与except捕获的异常的关系。

(1) raise [异常[(‘异常说明’)]]:表示raise的异常与except捕获的异常没有直接关系;

(2) raise 异常 from 变量:表示raise的异常由except捕获的异常导致;

(3) raise 异常 from None:不打印except捕获的异常;

1.2.1 raise

描述

raise [异常[(‘异常说明’)]]:表示raise的异常与except捕获的异常没有直接关系;

示例

>>> def testraise(s,i): try: print(s[i]) except IndexError: raise ValueError('i输入错误') >>> testraise('梯阅线条',5) Traceback (most recent call last): File "<pyshell#17>", line 3, in testraise print(s[i]) IndexError: string index out of range # raise [异常[('异常说明')]] , 捕获except的异常时,触发了另一个异常:raise的异常,两者无直接关系 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> testraise('梯阅线条',5) File "<pyshell#17>", line 5, in testraise raise ValueError('i输入错误') ValueError: i输入错误

1.2.2 raise from

描述

raise 异常 from 变量:表示raise的异常由except捕获的异常导致;

示例

>>> def testraise(s,i): try: print(s[i]) except IndexError as ie: raise ValueError('i输入错误') from ie >>> testraise('梯阅线条',5) Traceback (most recent call last): File "<pyshell#23>", line 3, in testraise print(s[i]) IndexError: string index out of range # raise 异常 from except的异常 , 是由except异常直接引发的 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> testraise('梯阅线条',5) File "<pyshell#23>", line 5, in testraise raise ValueError('i输入错误') from ie ValueError: i输入错误

1.2.3 raise from None

描述

raise 异常 from None:不打印except捕获的异常;

示例

>>> def testraise(s,i): try: print(s[i]) except IndexError as ie: # None 不打印 except的异常 raise ValueError('i输入错误') from None >>> testraise('梯阅线条',5) Traceback (most recent call last): File "<pyshell#27>", line 1, in <module> testraise('梯阅线条',5) File "<pyshell#26>", line 5, in testraise raise ValueError('i输入错误') from None ValueError: i输入错误

2 END

本文首发微信公众号:梯阅线条

更多内容参考python知识分享或软件测试开发目录。

文章转载自梯阅线条,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

文章被以下合辑收录

评论