The idea here is if there is an occasional error that causes your whole procedure to abort, but it is just an intermittent glitch that will work just fine if you wait a bit, you can just trap for the error and retry a few times.
But each time you retry, the wait time increases, since you don’t exactly know when the issue will clear. This is with Python 2.7.10.
import time tries = 1 wait = [1, 5, 10, 15] while tries <= 5: try: raise ValueError('Oops!') break except: if tries < 5: print "Retry after " + str(wait[tries - 1]) + " seconds." time.sleep(wait[tries - 1]) finally: tries = tries + 1
Here’s the output:
Retry after 1 seconds. Retry after 5 seconds. Retry after 10 seconds. Retry after 15 seconds.
In real life, the differences between the wait times are bigger. I did 1 minute, 5 minutes, 30 minutes, and an hour.
Also of course you would have your real code inside the try/except. The raise ValueError(‘Oops!’) is just to test the concept of the try/catch loop with increasing wait times.
If you know the exact exception, you can trap for it specifically, like below:
except ValueError as e:
where ValueError is substituted with the actual exception you are trapping for.