python的异常链

不喝水的杰 不喝水的杰 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

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

 

...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
不喝水的杰
不喝水的杰 宾川县微洛电子商务工作室官方账号 宾川县微洛电子商务工作室官方账号
鸿蒙Next开发者社区 31,487 成员 280 内容