Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If exception retry in Python

How could I go about doing something like this

  1. Try to do something.
  2. If it works, great, continue with normal flow.
  3. If it fails run a function and try again.
  4. If it once again fails throw an exception and stop code.

I believe I would have to make use of try but I haven't quite come around yet to how to use it in this particular example.

like image 910
Bernardo Meurer Avatar asked Jan 28 '26 22:01

Bernardo Meurer


2 Answers

It doesn't sound like you want to do a nested try-catch at all. Exceptions as control flow are a gnarly anti-pattern, and where you can avoid it, you should.

In this scenario, avoidance is easy. In the method that you describe, you want to be sure that a file exists before you do some operations on it. You also have a method to "correct" the path should it not. If both attempts fail, then you want to bail out.

With that into account, we would want to use os.path.isfile for this.

from os.path import isfile

def something(filepath):
    # Don't mutate the parameter if you can help it.
    p = filepath
    if not isfile(p):
        p = correct_path(p)
        if not isfile(p):
            raise Error("Cannot find file {} after correction to {}, aborting.".format(filepath, p))
    with open(p, 'r') as f:
        # Rest of file operations here
like image 62
Makoto Avatar answered Jan 31 '26 23:01

Makoto


This works for an arbitrary number of tries; I set it to two since that's what you want.

tries = 2
while True:
    try:
        step1()
    except CatchThisException:
        tries -= 1
        if tries:  # if tries != 0
            step3()
            continue  # not necessary, just for clarity
        else:
            raise  # step 4
    else:
        break  # step 2
like image 21
Cyphase Avatar answered Feb 01 '26 00:02

Cyphase