Handle an exception in a while loop

21,250

Solution 1

Try something like this:

def some_function(){
    try:
        #logic to load the page. If it is successful, it will not go to except.
        return True
    except:
        #will come to this clause when page will throw error.
        return False
    }
    
while(True):
    if some_function():
        break
    else:
        time.sleep(2)
        continue

Solution 2

Why not this:

res = False
while (res == False):
    time.sleep(2)
    try:
        some_function()
        res = boolean(some_function())
    except:
        continue

Solution 3

Everything in the try block is going to be executed until an Exception is raised, which case the except block wold be called.

So you're breaking during the first iteration.

I think you mean:

while(True):
    try:
        some_function()
    except:
        time.sleep(2)
        break

When the exception is raised, the while loop will be broken.

Share:
21,250
Luis Ramon Ramirez Rodriguez
Author by

Luis Ramon Ramirez Rodriguez

Updated on August 07, 2020

Comments

  • Luis Ramon Ramirez Rodriguez
    Luis Ramon Ramirez Rodriguez almost 4 years

    I'm calling a function that will raise an exception if a web page hasn't loaded yet. I want to wait 2 seconds and then try again until the page is loaded.

    I try this:

    while(True):
        try:
            some_funciont()
            break
        except:
            time.sleep(2)
    

    but it escapes after the first iteration.

    How do I escape if when the exception isn't raised?