我有一个while循环,检查2个 bool(boolean) 值是否为真。

try:
while bool1 == true or bool2 == true
    array1[n].dothing()
    array2[n].dothing()
    n= n+1
except IndexError
    bool1 = false

在while循环中,我从2个通常长度不同的未知数组中读取数据。我有一个异常,当到达array1的末尾时,IndexError会将bool1更改为false。是否可以有2个IndexError异常,每个数组一个,以便while循环仅在到达两个数组的末尾时才结束。我不知道语法,但看起来像
try:
while bool1 == true or bool2 == true
    array1[n].dothing()
    array2[n].dothing()
    n= n+1
except IndexError for array1
    bool1 = false
except IndexError for array2
    bool2 = false

这是可能的,还是将array2 [n] .dothing()放在第一个IndexError内部会更容易;将其扔到异常中听起来并不像是一种优雅的解决方案。

最佳答案

由于您要在任一数组用完时结束循环,因此哪个引发异常是否重要?这是您想做的事,但是如果您更好地解释用例,可能会有更简洁的方法。

while bool1 or bool2:
    try:
        array1[n].dothing()
    except IndexError:
        bool1 = False
    try:
        array2[n].dothing()
    except IndexError:
        bool2 = False
    n = n+1

关于python - 多案例异常处理python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35884389/

10-11 05:10