Python3通过回溯在多个故障上引发异常

时间:2018-04-16 18:53:57

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

在python 3中,可以链接异常,如下所示:

try:
  7/0
except ZeroDivisionError:
  raise ValueError("Invalid division")

# Traceback (most recent call last):
#   File "<stdin>", line 2, in <module>
# ZeroDivisionError: division by zero
#
# During handling of the above exception, another exception occurred:
#
# Traceback (most recent call last):
#   File "<stdin>", line 4, in <module>
# ValueError: Invalid division

如果我遇到以下情况怎么办?

  • 具有可能成功或抛出错误的方法的类。
  • 我在列表中有一堆该类的实例。
  • 我在某个地方为列表中的每个实例调用该方法。
  • 他们中的一个成功就足够了。如果每个实例都失败,我会抛出一个错误。

现在,如果我必须抛出错误,我想打印在列表中每个实例的测试期间抛出的所有异常。代码澄清:

instances_to_test = [instance0, instance1, instance2]
failures = [] # List of all the thrown exceptions
success = False # True if one of the instances in the list succeeds
for instance in instances_to_test:
  try:
    instance.method_may_raise() # May raise an Error
    success = True
    break
  except Exception as e:
    failures.append(e)
if not success:
  # ... What to do here ...

评论中该行的理想解决方案如下所示:

if not success:
  raise MultipleFailException("Could not find an adequate instance", parents=failures)

# 0 ------------------------------------
#
# Traceback (most recent call last):
#   File "<stdin>", line 6, in <module>
# ValueError: Message of instance0
#
# 1 ------------------------------------
#
# Traceback (most recent call last):
#   File "<stdin>", line 6, in <module>
# ValueError: Message of instance1
#
# 2 ------------------------------------
# Traceback (most recent call last):
#   File "<stdin>", line 6, in <module>
# ValueError: Message of instance2
#
# During handling of the above exception(s), another exception occurred:
#
# Traceback (most recent call last):
#   File "<stdin>", line 12, in <module>
# MultipleFailException: Could not find an adequate instance

这可以用'干净'的方式完成,还是应该像python 2天那样摆弄堆栈跟踪?

0 个答案:

没有答案