小编Nim*_*rod的帖子

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

有没有办法将try/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", …
Run Code Online (Sandbox Code Playgroud)

python error-handling exception-handling exception

6
推荐指数
1
解决办法
2228
查看次数