具有Java异常的Python等效原因 - python

Python中是否有一种引发错误的原因,该错误以另一个错误为原因?

在Java中,您可以创建一个原因异常的实例,例如以下代码

try {
    throw new IOException();
} catch (IOException e) {
    throw new RuntimeException("An exception occurred while trying to execute", e);
}

导致出现此错误消息:

Exception in thread "main" java.lang.RuntimeException: An exception occurred while trying to execute
    at thing.Main.main(Main.java:11)
Caused by: java.io.IOException
    at thing.Main.main(Main.java:9)

请注意,第一个异常(在堆栈跟踪中)由第二个“引起”。

我认为,这是向API用户显示调用期间发生了更高级别错误的好方法,开发人员可以通过查看较低级别异常(它是更高级别的“原因”)来调试它级别错误(在这种情况下,RuntimeException是由IOException引起的)。

通过我的搜索,我无法找到有关将错误作为Python中另一个错误的原因的信息。可以在Python中实现吗?怎么样?如果没有,那么Pythonic的等效物是什么?

参考方案

在Python中,它是通过非常相似的结构实现的:

try:
    raise ValueError
except ValueError:
    raise ValueError('second exception')

这将生成以下回溯:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    raise ValueError
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    raise ValueError('second exception')
ValueError: second exception

raise from是Python的另一个功能,它提供了稍微不同的回溯:

try:
    raise ValueError
except ValueError as e:
    raise ValueError('second exception') from e

追溯:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    raise ValueError
ValueError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    raise ValueError('second exception') from e
ValueError: second exception

进一步阅读:

pep-3134
this SO answer

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

在屏幕上打印错误,但继续执行代码 - python

我有一些代码可以通过一系列URL进行迭代。如果由于其中一个URL不包含有效的JSON正文而导致我的代码中出现错误,我希望将生成的错误打印到屏幕上,然后将代码移至下一个迭代。我的代码的简单版本是:for a in myurls: try: #mycode except Exception as exc: print traceback.format_exc()…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…