for _ in range(5):
try:
# replace this with something that may fail
raise ValueError("foo")
# replace Exception with a more specific exception
except Exception as e:
err = e
continue
# no exception, continue remainder of code
else:
break
# did not break the for loop, therefore all attempts
# raised an exception
else:
raise err
My version is similar to several of the above, but doesn't use a separate while
loop, and re-raises the latest exception if all retries fail. Could explicitly set err = None
at the top, but not strictly necessary as it should only execute the final else
block if there was an error and therefore err
is set.