如何创建具有多种原因的python异常?

时间:2019-03-07 16:01:17

标签: python python-3.x python-2.7 exception

如何引发具有多种原因的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解决方案。所有回溯和异常消息都必须保留。

3 个答案:

答案 0 :(得分:2)

仅在创建最后一个异常时将异常作为参数传递。

for method in methods_to_try:
    try:
        method()
    except Exception as e:
        exceptions.append(e)
if exceptions:
    raise Exception(*exceptions)

它们将通过args属性可用。

答案 1 :(得分:1)

一次可以从另一个引发每个异常以将其链接起来。唯一的问题是原因顺序可能会产生误导。

def combine_exc(exceptions):
   c_exc = None
   for ex in reversed(exceptions):
      try:
         if c_exc is None:
            raise ex
         else:
            raise ex from c_exc
      except Exception as ex1:
         c_exc = ex1

   return c_exc

答案 2 :(得分:0)

改为使用日志记录

如果您可以使用日志记录模块,我想记录您捕获的单个异常并且只引发一个整体异常是最干净的方法。

如果您只想输出日志消息以防所有尝试的函数出错,那么对于logging cookbook中的缓冲记录器来说,这是一个理想的情况 您可以对其进行修改,使其始终以调试级别记录日志,但如果所有子功能均引发错误,则将级别提高至错误。