What is the most elegant way to repeat something after it caused an exception in python?
I have something like this [pseudo code as an example]:
try:
do_some_database_stuff()
except DatabaseTimeoutException:
reconnect_to_database()
do_some_database_stuff() # just do it again
But imagine if I don't have a nice function but a lot of code instead. Duplicate code is not very nice.
So I think this is slightly better:
while True:
try:
do_some_database_stuff()
break
except DatabaseTimeoutException:
reconnect_to_database()
That's 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 really know if it worked so it's also:
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 it starts to get very messy.
What is the most elegant way of expressing this logic?
You can use a "for-else" loop:
for ii in range(5):
try:
do_some_database_stuff()
break
except DatabaseTimeoutException:
reconnect_to_database()
else:
raise DatabaseTimeoutException
Or, without:
for ii in range(5):
try:
do_some_database_stuff()
break
except DatabaseTimeoutException:
if ii == 4:
raise
reconnect_to_database()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With