break if an error happened multiple times

Viewed 64

is there a way that I can handle errors by how many times the error happens?

like I'm handling an error by exception like this

except NoSuchElementException:
     driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
     sleep(randint(2,3))
     continue

then I want if error except NoSuchElementException: happened like 5-6 times print something like job is done and break

how I am able to do that?

note: the above code is in a loop like for i in itertools.count(start=1):

2 Answers

How about counting the number of occurrence of exceptions in a variable? Here is a toy example.


ERROR_COUNT = 0

while True:
    val = int(input('NUM: '))
    try:
        if val < 0:
            # Your exception here.
            raise ValueError('Negative number entered.')
        else:
            print('good.')

    except ValueError:
        ERROR_COUNT += 1
        if ERROR_COUNT >= 5:
            break

Since you have a loop inside which you are trying something you can define errors counter before that loop and increment it in case of error.
Something like this:

error_counter = 0
for i in itertools.count(start=1):
    try something:
        ------
        ------
    except NoSuchElementException:
        driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN)
        error_counter = error_counter + 1
        if(error_counter>4):
            print("Error occurred " + error_counter + " times. Job is done")
            break
        sleep(randint(2,3))
        continue
Related