python中的多异常处理程序

2024-04-20 05:50:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写的代码必须处理许多IndexError异常。
所以,我使用了^{cd2>}块:

try:
    <do some level_1 calculations>
except IndexError:
    <change to level_2 calculations>  

但是,如果我的异常处理程序再次引发另一个IndexError,该怎么办?
如何安全地在此代码结构中放置另一个IndexError异常,以便如果级别2计算再次被IndexError捕获,那么代码将再次作为异常运行“级别3计算”,以此类推。你知道吗


Tags: to代码处理程序some级别change结构level
3条回答

通常,在编写代码时,您应该知道在任何阶段都可能发生什么,并且应该相应地放置异常处理程序。你知道吗

也就是说,如果您正在执行一系列操作,其中有多个位置可能导致特定的异常,那么您可以将整个块封装到一个适当类型的异常处理程序中。在其他情况下,当由于某些其他异常而需要不同的行为时,请定义单独的处理程序。你知道吗

这两种方法在逻辑上都是正确的,这是一个设计问题。你知道吗

将计算/函数放入列表中:

from random import choice
from operator import mul, add

funcs = [mul, add]

for f in funcs:
    try:
        i = l[choice([1, 2, 3])]
        calc = f(i[0], i[1])
        print(calc)
        break # break if you want the first successful calc to be the last
    except IndexError as e:
        print(e)
        continue

如果你运行代码,你会看到随机索引器被捕获。你知道吗

您可以嵌套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>

相关问题 更多 >