Python: 如何在包含多个Except块的Try/Except语句中传递异常

7

在try/except块中,有没有一种方法可以将异常从一个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块中的通用错误处理不适用。
目前我唯一的解决方法是在第一个块中也包含通用错误处理代码。即使将其包装在自己的函数块中,它似乎仍然不够优雅...

你可以将通用的错误处理放在一个函数中,然后在两个地方调用它,这样会更加优雅。 - depperm
1
在Python中是不可能的:执行不能从一个try/exceptif/elif/else块跳到另一个块。这就像铁路交叉口:你全速前进,要么向左转,要么向右转,如果你已经选择了一条路,就无法将火车移动到另一条分支上。 - ForceBru
1个回答

6
你有两个选项:
  • Don't catch IndexError with a dedicated except .. block. You can always test manually for the type of exception in the general block by catching BaseException and assigning the exception to a name (here 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
    
  • Use nested try..except statements and re-raise:

    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
    

所以基本上我的问题的答案是“不”。但至少我们有三种不同的解决方法。谢谢 ;) - Nimrod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接