python的异常链

不喝水的杰 荣耀黄金
宾川县微洛电子商务工作室官方账号
2022-09-05 22:09:14

raise 语句支持可选的 from 子句,该子句用于启用链式异常。 例如:

# exc must be exception instance or None.
raise RuntimeError from exc

转换异常时,这种方式很有用。例如:

>>>

>>> def func():
...     raise ConnectionError
...
>>> try:
...     func()
... except ConnectionError 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
ConnectionError

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

异常链会在 except 或 finally 子句内部引发异常时自动生成。 这可以通过使用 from None 这样的写法来禁用:

>>>

>>> try:
...     open('database.sqlite')
... except OSError:
...     raise RuntimeError from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError

 

...全文
18 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

30,758

社区成员

发帖
与我相关
我的任务
社区描述
鸿蒙Next技术问题交流和学习资源共享中心
vue.js前端harmonyos 个人社区
社区管理员
  • 言程序plus
  • 小   明
  • 叶落秋白
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

web全栈技术交流中心

试试用AI创作助手写篇文章吧