【问题标题】:Python: Propagate an exception through a Try/Except Block with multiple ExceptsPython:通过具有多个异常的 Try/Except 块传播异常
【发布时间】:2017-05-13 21:02:24
【问题描述】:

有没有办法将 try/except 块中的异常从一个 except 传播到下一个?

我想捕获一个特定的错误,然后也进行一般的错误处理。

“raise”是让异常“冒泡”到外部 try/except,但不在引发错误的 try/except 块内。

理想情况下应该是这样的:

import logging

def getList():
    try:
        newList = ["just", "some", "place", "holders"]
        # Maybe from something like: newList = untrustedGetList()

        # Faulty List now throws IndexError
        someitem = newList[100]

        return newList

    except IndexError:
        # For debugging purposes the content of newList should get logged.
        logging.error("IndexError occured with newList containing: \n%s",   str(newList))

    except:
        # General errors should be handled and include the IndexError as well!
        logging.error("A general error occured, substituting newList with backup")
        newList = ["We", "can", "work", "with", "this", "backup"]
        return newList

我遇到的问题是,当 IndexError 被第一个 except 捕获时,我在第二个 except 块中的一般错误处理没有应用。

我目前唯一的解决方法是将一般错误处理代码也包含在第一个块中。即使我将它包装在它自己的功能块中,它仍然看起来不够优雅......

【问题讨论】:

  • 你可以在一个函数中处理一般错误,然后在两个地方调用它,稍微优雅一点
  • 不可能(至少在 Python 中):执行不能从一个 try/exceptif/elif/else 块跳转到另一个块。这就像一个铁路枢纽:您全速行驶,向左或向右行驶,如果您已经乘坐了一个分支,则无法将火车移动到另一个分支。

标签: python exception error-handling exception-handling


【解决方案1】:

你有两个选择:

  • 不要用专用的except .. 块捕获IndexError。您始终可以通过捕获 BaseException 并将异常分配给名称(此处为 e)手动测试常规块中的异常类型:

    try:
        # ...
    except BaseException as e:
        if isinstance(e, IndexError):
            logging.error("IndexError occured with newList containing: \n%s",   str(newList))
    
        logging.error("A general error occured, substituting newList with backup")
        newList = ["We", "can", "work", "with", "this", "backup"]
        return newList
    
  • 使用嵌套的try..except 语句并重新引发:

    try:
        try:
            # ...
        except IndexError:
            logging.error("IndexError occured with newList containing: \n%s",   str(newList))
            raise
    except:
        logging.error("A general error occured, substituting newList with backup")
        newList = ["We", "can", "work", "with", "this", "backup"]
        return newList
    

【讨论】:

  • 所以基本上我的问题的答案是否定的。但至少有 3 种不同的解决方法。谢谢 ;)
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 2017-05-20
  • 2010-10-22
相关资源
最近更新 更多