Sam
Sam

Reputation: 323

Multicased exception handling python

I have a while loop that checks if 2 booleans are true.

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

inside the while loop I'm reading from 2 arrays of unknown usually different length. I have an exception for IndexError to change the bool1 to false when the end of array1 is reached. Is it possible to have 2 IndexError exceptions, one for each array so that the while loop ends only when the end of both arrays are reached. I dont know the syntax but something that looks like

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

Is this possible or would it be easier to just have array2[n].dothing() inside of the first IndexError; throwing it inside the exception doesnt sound like an elegant fix.

Upvotes: 0

Views: 29

Answers (1)

Srikanth
Srikanth

Reputation: 1003

Since you are ending the loop when either array runs out, does it matter which one raised the exception? Here's how to do what you want to do, but there may be a more cleaner way if you explain your use case better.

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

Upvotes: 1

Related Questions