首页 > 解决方案 > 在 `raise RuntimeError('Failed to open database') from exc 中使用 `from exc` 的目的是什么?

问题描述

https://docs.python.org/3/tutorial/errors.html#exception-chaining

>>>
>>> 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

当在 except 或 finally 部分中引发异常时,异常链接会自动发生。那么使用from excin的目的是raise RuntimeError('Failed to open database') from exc什么?不是隐含的吗?

标签: python

解决方案


您可以随时查看引入某个功能的 PEP。在这种情况下,您可以阅读PEP 3141的这一部分。

语法的使用raise EXCEPTION from CAUSE允许显式链接异常。就像该页面上给出的示例一样,如果您只想在 API 中引发某个错误,但又想突出显示引发问题的原始异常,则可以使用这种链接异常的方式。

所以它只是提供了一种更明确的方式来做到这一点,而“正常”语法raise EXCEPTION只是隐式地链接异常。

这可以理解吗?如果您不明白,请告诉我。


推荐阅读