How to retry in the same line after exception?

Viewed 46

I have the following code:

def my_function:
    #operation 1
    #operation 2
    ...
    #operation 99
    #operation 100

def handle_exception:
    #handle exception

Now, during any part of executing my_function an exception might occur. If it does, I want to handle it by calling handle_exception method. And then go back to my_function and retry the same operation that caused the exception. If it works this time, continue with the code. The exceptions might happen in random places in the code and I don't want to retry whole my_function.

So for example. I am executing my_function. Operation 1 worked correctly. During operation 2 there was an exception. I handle the exception and then try operation 2 again. It works this time so I continue with operations.

Is this possible in Python?

1 Answers

I would do this:

def my_function(start = 0):

    def operation1():
        ...
    def operation2():
        ...
    oper = [operation1, operation2]
   
    for index in range(start, len(oper)):
        try:
            oper[index]()
        except:
            handle_exception(index)
            break
def handle_exception(index):
    #handle exception
    my_function(index)

Of course you need the function handle_exception to solve the problem, otherwise it will lead to infinite recursion

Here is an example to understand how the code works:

def my_function(start = 0):

def operation1():
    global i
    print(i[2])
def operation2():
    print(2)
oper = [operation1, operation2]

for index in range(start, len(oper)):
    try:
        oper[index]()
    except:
        handle_exception(index)
        break
def handle_exception(index):
    global i
    i = ["a", "b", "c"]
    my_function(index)

i = ["a", "b"]
my_function()

Note that the function handle_exception fixes the i list, so that there will not be an index error.

Related