A. t A. t - 1 year ago 82
Python Question

Python3 error handling

Here is my Python3 program.

while true:
except NewConnectionError:
print('error detection')

I thought when above program catches NewConnectionError it goes back to "A" after printing a log. But it doesn't.

How do I change above codes to restart "A" recursively when the program catching Error.


Not only restarting, but keeping running is also good for me.
Thanks for quickly replying.

Answer Source

Encapsulate the try/except blocks inside the while loop (not the other way around):

while True:
    except NewConnectionError as err:
        # This will also print the reason the exception occurred
        print ('Detected error: {}'.format(err))
        print("A() returned successfully.")
        print ("Next loop iteration...")

You can safely omit the else and finally blocks. I have only included them for illustrative purposes.

else is only executed if an exception does NOT occur (that is, if the statements in the try block were successful).

finally is always executed regardless whether an exception occurs or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download