有没有办法将 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/