Eva*_*van 5 python exception python-2.7 python-3.x
如何引发具有多种原因的 python 异常,类似于 Java 的addSuppressed()功能?例如,我有多种要尝试的方法的列表,如果它们都不起作用,我想引发一个异常,其中包括所有已尝试的方法的异常。IE:
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
Run Code Online (Sandbox Code Playgroud)
但是这段代码失败了,因为该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)
Run Code Online (Sandbox Code Playgroud)
它们将在属性中可用args。