品易云推流 关闭
文章详情页
文章 > Python基础教程 > python异常链是什么

python异常链是什么

python异常链

头像

小妮浅浅

2021-07-29 09:25:113168浏览 · 0收藏 · 0评论

说明

1、当通过except捕捉到一个异常A后,可以用raise语句再次抛出一个异常B。

然后我们看到的异常信息是B的信息。但我们不知道这个异常B来自哪里,此时,我们可以使用异常链。

2、在抛出异常链时,使用raisefrom语句。

实例

>>> def func():
...     raise IOError
...
>>> try:
...     func()
... except IOError as exc:
...     raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in func
OSError
 
The above exception was the direct cause of the following exception:
 
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database

以上就是python异常链的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图