Python try / except keep trying until no errors

10,046

Solution 1

Here's one way to do it if you don't want to use a loop. Just recall the function on the exception

 import sys

 def init_driver(tries=0):

     try:
         ffprofile = webdriver.FirefoxProfile("my_profile");
         ffprofile.add_extension(extension="myaddon.xpi")
         return driver

     except Exception: #This should be the exception you expect and not a catch all
         if tries < sys.getrecursionlimit(): #By default 1,000 can be bumped up by setrecursionlimit
             return init_driver(tries+1)
         #just for kicks
         #else:
             #sys.setrecursionlimit(sys.getrecursionlimit() + 1)
             #print("Yes we'll win this game the old-fashioned way, the tried and true way:")
             #print("We'll cheat!")
             #refactor / prettify if's to call init_driver if you want to cheat.
         else:
             print("OH NO RECURSION LIMIT HIT!!!!!! (ノಠ益ಠ)ノ彡┻━┻")

 driver = init_driver()

Solution 2

Here's a loop that iterates over attempts:

while True:
    try:
        driver = init_driver()
        break
    except Foo:
        continue

Note that this is not a bare except clause. Bare excepts are dangerous because they can capture things like NameError that are so rarely meant to be caught. You should put the specific exception you expect to catch here.

Solution 3

Other answers are fine but they will keep retrying until it hits the recursion depth limit. Consider adding a retry limit:

def init_driver(retry_limit=10, nretry=0):
    if nretry >= retry_limit:
       return # retry limit reached, maybe raise an exception?
    try:
        ffprofile = webdriver.FirefoxProfile("my_profile");
        ffprofile.add_extension(extension="myaddon.xpi")
    except SomeException:
        return init_driver(nretry=nretry+1)
    return ffprofile

driver = init_driver()

Solution 4

Here is a recursive solution (with keeping track of the retries):

def init_driver(retries=0):
    try:
        ffprofile = webdriver.FirefoxProfile("my_profile");
        ffprofile.add_extension(extension="myaddon.xpi")
    except:
        print('attempt nr. ' + str(retries))
        return init_driver(retries+1)
    return driver

Solution 5

Do like this:

def init_driver():
    driver = None
    ffprofile = webdriver.FirefoxProfile("my_profile");
    ffprofile.add_extension(extension="myaddon.xpi")
    # do something with a valid profile and set driver to something other than None
    return driver

driver = None
while driver is None:
    driver = init_driver()
Share:
10,046
fightstarr20
Author by

fightstarr20

Boldly going.....

Updated on June 17, 2022

Comments

  • fightstarr20
    fightstarr20 almost 2 years

    I have the following code that occasionally crashes due to a permissions bug. I am trying to wrap it up in a try / except statement that will keep trying to launch the driver until successful...

    def init_driver():
        ffprofile = webdriver.FirefoxProfile("my_profile")
        ffprofile.add_extension(extension="myaddon.xpi")
        return driver
    
    driver = init_driver()
    

    I have seen examples letting me print a message if an error occurs but how do I get it to keep retrying? Does anybody have an example they can point me at?

  • user2390182
    user2390182 about 8 years
    Need to return init_driver() in the except-block
  • MS-DDOS
    MS-DDOS about 8 years
    Technically recursive solutions will stop retrying after it hits the recursion depth limit set by python. By default this is 1,000 so setting a smaller limit not based on maximum recursion depth is probably wise.
  • MS-DDOS
    MS-DDOS about 8 years
    Lol thank you for adding in the recursion limit conditions.
  • Pythonista
    Pythonista about 8 years
    Welcome lol. I didn't even think about it until you commented. Thought I'd try to make it differ some from other posts since we're all very self-similar in our answers.
  • MS-DDOS
    MS-DDOS about 8 years
    Also resetting the recursion limit will actually work until you get a...wait for it...stack overflow
  • TigerhawkT3
    TigerhawkT3 about 8 years
    It doesn't really matter for a statement like break, but technically you want to try only init_driver(), and if it succeeds, then you break. That is more canonically expressed with else: break after the except block. Again, not much difference for just break, but moving it to the else can look more clear (also good practice for when it's something more complex than break).