A. t A. t - 2 months ago 16
Python Question

Python3 error handling

Here is my Python3 program.

try:
while true:
A
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.

Thanks.

P.S.
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:
    try:
        A()
    except NewConnectionError as err:
        # This will also print the reason the exception occurred
        print ('Detected error: {}'.format(err))
    else:
        print("A() returned successfully.")
    finally:
        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.