加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:39:02 所属栏目:Python 来源:网络整理
导读:如何引发具有多种原因的python异常,类似于Java的addSuppressed()功能?例如,我有多种尝试方法的列表,如果它们都不起作用,我想引发一个异常,其中包括所有尝试过的方法的异常.即: exceptions = []for method in methods_to_try: try: method() except Excepti

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

最佳答案
创建最后一个异常时,只需将异常作为参数传递即可.

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

它们将在args属性中可用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读