python - 在 `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 exc
in的目的是raise RuntimeError('Failed to open database') from exc
什么?不是隐含的吗?
解决方案
您可以随时查看引入某个功能的 PEP。在这种情况下,您可以阅读PEP 3141的这一部分。
语法的使用raise EXCEPTION from CAUSE
允许显式链接异常。就像该页面上给出的示例一样,如果您只想在 API 中引发某个错误,但又想突出显示引发问题的原始异常,则可以使用这种链接异常的方式。
所以它只是提供了一种更明确的方式来做到这一点,而“正常”语法raise EXCEPTION
只是隐式地链接异常。
这可以理解吗?如果您不明白,请告诉我。
推荐阅读
- python - Python 类装饰器“self”似乎是错误的
- sql - SSIS:如何使用 Foreach 循环容器创建表?
- codeigniter-3 - Codeigniter 上传文件有时不起作用
- python - Django主页测试错误
- shell - 如何逐列比较同一文件中的 3 行,如果有任何不匹配则返回 FALSE
- ios - 使用未解析的标识符“NSFontAttributeName”
- r - 从子矩阵中提取
- visual-studio - 更新到 Windows 10 并安装 Visual Studio 2017 后出现 Xamarin 表单错误
- python-3.x - ValueError:检查输入时出错:预期 input_1 的形状为 (None, 1) 但得到的数组的形状为 (5, 54)
- django - 504 error when the view loading takes more than 5 s