I need to invoke method f
. If it raises an IOError
, I need to invoke it again (retry), and do it at most three times. I need to log any other exceptions, and I need to log all retries.
the code below does this, but it looks ugly. please help me make it elegant and pythonic. I am using Python 2.7.
thanks!
count = 3
while count > 0:
try:
f()
except IOError:
count -= 1
if count > 0:
print 'retry'
continue
except Exception as x:
print x
break
Python while loop exception continue If a statement is systematically correct then it executes the programm. Exception means error detection during execution. In this example, we can easily use the try-except block to execute the code.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.
If you have try catch within the loop it gets executed completely inspite of exceptions.
Use try .. except .. else
:
for i in range(3, 0, -1):
try:
f()
except IOError:
if i == 1:
raise
print('retry')
else:
break
You should not generically catch all errors. Just let them bubble up to the appropriate handler.
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