Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retry after exception?

I have a loop starting with for i in range(0, 100). Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will continue in the except clause (continue on to the next number for i).

Is it possible for me to reassign the same number to i and run through the failed iteration of the loop again?

like image 757
FurtiveFelon Avatar asked Jan 18 '10 05:01

FurtiveFelon


People also ask

How do you implement a re try catch?

Instead of asking if it's empty, I sourround the actions in a try-catch (which under concurrency becomes compulsory even with the previous if). In such a case, in the catch block I would ask to refill the queue with more elements and then, retry. Voila.

What happens when you raise exception?

While syntax errors occur when Python can't parse a line of code, raising exceptions allows us to distinguish between regular events and something exceptional, such as errors (e.g. dividing by zero) or something you might not expect to handle.


2 Answers

Do a while True inside your for loop, put your try code inside, and break from that while loop only when your code succeeds.

for i in range(0,100):     while True:         try:             # do stuff         except SomeSpecificException:             continue         break 
like image 176
zneak Avatar answered Oct 05 '22 18:10

zneak


I prefer to limit the number of retries, so that if there's a problem with that specific item you will eventually continue onto the next one, thus:

for i in range(100):   for attempt in range(10):     try:       # do thing     except:       # perhaps reconnect, etc.     else:       break   else:     # we failed all the attempts - deal with the consequences. 
like image 31
xorsyst Avatar answered Oct 05 '22 18:10

xorsyst