0

This is quite tricky to explain, but I'd like to know if there is a way to repeatedly retry only the line of code that produced the error until it works. For example say I have the code:

def unreliabelfunction():
    #Line 1 of code
    #Line 2 of code (sometimes produces an error and sometimes works)
    #Line 3 of code

#Error handling should go where function is called, rather than inside the function.
unreliablefunction()

I would like to have some sort of error handling that would continually run line 2 until it worked (without rerunning line 1) and then continue with the rest of the function. In addition, I would like the error handling to be outside of the function and not to change the function itself.

I hope this makes sense and thank for your help :)

TheFluffDragon9
  • 514
  • 5
  • 11

1 Answers1

0

You are looking for a try: except block.

Here's a rough example.

def unreliabelfunction():
    line_1()
    try_wrapper(line_2())
    line_3()

# Pass a function to try_wrapper
def try_wrapper(fn, args):
    successful = False
    while not successful:
        try:
            # Execute the function.
            fn(*args)
            # If it doesn't cause an exception, 
            # update our success flag.
            successful = True
        # You can use Exception here to catch everything, 
        # but ideally you use this specific exception that occurs.
        # e.g. KeyError, ValueError, etc.
        except Exception:
            print("fn failed! Trying again.") 

See the docs: https://docs.python.org/3/tutorial/errors.html#handling-exceptions

puppydog
  • 385
  • 3
  • 14
  • Yes I an aware of that but that would retry the entire function instead of just line 2 onwards, which is what I'm after. Thanks for your answer though! – TheFluffDragon9 May 05 '20 at 14:55
  • Ah. You could still use that code. Let me update the original response. – puppydog May 05 '20 at 14:56
  • There is no good way to do it for an individual "line" of code, but you can break your original function down into multiple functions and use the updated pattern above. – puppydog May 05 '20 at 14:59
  • Yeah okay I thought that might be the case: Unfortunately I cannot edit the function though – TheFluffDragon9 May 05 '20 at 15:01
  • Hm. You'll just have to try: except the entire function call then, unfortunately. – puppydog May 05 '20 at 15:07