在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天那样摆弄堆栈跟踪?