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

前端之家收集整理的这篇文章主要介绍了如何创建具有多种原因的python异常? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

如何引发具有多种原因的python异常,类似于JavaaddSuppressed()功能?例如,我有多种尝试方法的列表,如果它们都不起作用,我想引发一个异常,其中包括所有尝试过的方法的异常.即:

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属性中可用.

原文链接:https://www.f2er.com/python/533195.html

猜你在找的Python相关文章