What is the most elegant way to repeat something after it throws an exception in python?
I have something like this [example pseudo code]:
try: do_some_database_stuff() except DatabaseTimeoutException: reconnect_to_database() do_some_database_stuff()
But imagine if I don't have a nice feature, but a lot of code. Duplicated code is not very nice.
So, I think this is a little better:
while True: try: do_some_database_stuff() break except DatabaseTimeoutException: reconnect_to_database()
This is good enough if the exception really fixes the problem. If not, I need a counter to prevent an indefinite loop:
i = 0 while i < 5: try: do_some_database_stuff() break except DatabaseTimeoutException: reconnect_to_database() i += 1
But then I don't know if this works like this:
while i <= 5: try: do_some_database_stuff() break except DatabaseTimeoutException: if i != 5: reconnect_to_database() else: raise DatabaseTimeoutException i += 1
As you can see, this is starting very unpleasantly.
What is the most elegant way to express this logic?
- try something
- If this fails, correct
- try a few more times including fix
- if it continues to fail gives me an error to prevent an indefinite loop
source share