Python:通过具有多个 Excepts 的 Try/Except block 传播异常

标签 python exception error-handling exception-handling

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

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

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

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

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 block 中的一般错误处理没有应用。

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

最佳答案

你有两个选择:

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

    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
    

关于Python:通过具有多个 Excepts 的 Try/Except block 传播异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41381360/

相关文章:

python - 无法弄清楚如何在此 Python 代码中重新分配列表列表中的元素

c++ - 如何在C++中进行错误处理和捕获

angularjs - ASP.NET Core Web Api 向 AngularJS $http promise 返回错误消息

python - python3中的低级自省(introspection)?

python - Django Admin 显示来自 Imagefield 的图像

python - 一个带有 'while' 的线程 python 得到另一个线程从未启动

c# - 如何在 C# 中显示该方法成功返回或失败而不返回值?

c++ - 使用 -O2 或 -O3 标志编译时未捕获异常

c# - 检测到绑定(bind)失败 'Microsoft.Practices.EnterpriseLibrary.Validation'

c# - ASP.NET MVC 4 错误处理