我正在编写必须处理许多IndexError
异常的代码。
因此,我使用了try except
块:
try:
<do some level_1 calculations>
except IndexError:
<change to level_2 calculations>
但是,如果我的异常处理程序再次引发另一个IndexError
怎么办?
如何安全地在此代码结构中放置另一个IndexError
异常,以便如果再次将level_2计算捕获到IndexError
中,则代码将再次作为异常运行“ level_3计算”,依此类推。
python大神给出的解决方案
您可以嵌套try except
块,如下所示:
try:
<do some level_1 calculations>
except IndexError:
try:
<change to level_2 calculations>
except IndexError:
try:
<change to level_3 calculations>
except IndexError:
<change to level_4 calculations>
但这看起来很混乱,如果您弄乱了格式,可能会造成麻烦,最好使用一系列函数,这些函数会循环尝试不同的计算,直到所有计算均失败,然后再以其他方式处理异常。
calulators = [
level_1_calculation_function,
level_2_calculation_function,
level_3_calculation_function,
]
for attempt in range(len(calculators)):
try:
result = calculators[attempt]
break #If we've reached here, the calculation was successful
except IndexError:
attempt += 1
else:
#If none of the functions worked and broke out of the loop, we execute this.
<handle_exception>