在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块中的通用错误处理不适用。
目前我唯一的解决方法是在第一个块中也包含通用错误处理代码。即使将其包装在自己的函数块中,它似乎仍然不够优雅...
try/except
或if/elif/else
块跳到另一个块。这就像铁路交叉口:你全速前进,要么向左转,要么向右转,如果你已经选择了一条路,就无法将火车移动到另一条分支上。 - ForceBru