如何引发具有多种原因的 python 异常,类似于 Java 的 addSuppressed()特征?例如,我有多个要尝试的方法列表,如果它们都不起作用,我想引发一个异常,其中包括所有已尝试方法的异常。即:
exceptions = []
for method in methods_to_try:
try:
method()
except Exception as e:
exceptions.append(e)
if exceptions:
raise Exception("All methods failed") from exceptions
但是这段代码失败了,因为 raise ... from ...
语句需要一个异常而不是一个列表。 Python 2 或 3 解决方案是可以接受的。必须保留所有回溯和异常消息。
最佳答案
在创建最后一个异常时将异常作为参数传递。
for method in methods_to_try:
try:
method()
except Exception as e:
exceptions.append(e)
if exceptions:
raise Exception(*exceptions)
它们将在 args
属性中可用。
关于python - 如何创建具有多种原因的 python 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55048047/