【发布时间】: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/except或if/elif/else块跳转到另一个块。这就像一个铁路枢纽:您全速行驶,向左或向右行驶,如果您已经乘坐了一个分支,则无法将火车移动到另一个分支。
标签: python exception error-handling exception-handling