Search code examples
pythonpython-3.xtry-catchtry-except

Is it possible to run try statement in a loop if any error comes?


If some error comes then it goes to except statement after the try one, where the program ends. My question is, Is it possible, that if an error comes then without ending the program it runs the try statement continuously?

For example :

try:
    some error caught
except:
    go to try statement again

And this runs continuously in a chain?


Solution

  • Just create a loop, that breaks if no exception occurs

    while True:
       try:
           some_code_that_might_fail
        except Exception:  # catch all potential errors 
            continue  # if exception occured continue the loop
        break  # if no exception occured break out of the loop
    

    Pls try out following example:

    while True:
        try:
            num = int(input("please enter a number"))
            print("The number is ", num)
            rec = 1 / num
        except Exception:
            print("either you entered no number or 0 (or some other error occured)")
            continue  # if any exception occured continue the loop
        break  # if no exception occured break out of the loop
    
    print("1 / %f = %f" % (num, rec))
    
    

    As Bruno mentioned. In general (and this is what I do in my own code) it is not suggested to catch all exceptions.

    You should catch only known exceptions explicitly

    Addendum 2020-04-17

    Reading your answer I think your question is a little misleading. What is perhaps your problem is, that you have a function, that you would like to run forever. However sometimes the function terminates (due to an error) without raising an exception.

    IF this is the case then just write:

    while True:
       afunc()
       print("function terminated. I will restart it")
    

    but note, that your program will never terminate.

    or if the function sometimes raises an exception and sometimes doesn't but just terminates and you'd like to call the function whenever it failed or terminated, then do.

    while True:
       try:
          afunc()
          print("function terminated without exception")
    
       except Exception:
          pass
          print("function encountered an exception")
       print("will restart")
    
    

    If you want, that function can terminate and you have the means to find out whether it was an error or not, then you could do something like:

    while True:
       try:
          afunc()
          if i_know_that_func_terminated_correctly():
              print("function terminated correctly")
              break
          print("function terminated without an error")
    
       except Exception:
          pass
          print("function terminated with an exception")
       print("restarting")
    
    

    I added print statements for debugging / visualizing. Just remove them or comment them if not needed. (That's also why I left the pass statement in the except clause)