I have got the following piece of code, so that while any exception occurs, re-do this loop, instead of jumping to the next loop. Please note the pseudo code here does work as intended:
for cl in range(0, 10):
try:
some_function(cl)
except :
cl -= 1
My initiative was that once something go wrong, do it again. Obviously, this is not a working idea. So given the assumption that the for
loop and range function
being used, how to implement the control that I described?
Thanks
You simply need a second loop inside the first to continue trying the function until it works:
for cl in range(0, 10):
while True:
try:
some_function(cl)
except Exception:
continue # try it again
else:
break # exit inner loop, continue to next c1
For more control over the loop variable, you might want to use a while
loop:
cl = 0
while cl < 10:
try:
some_function(cl)
cl += 1
except:
pass
In Python, the pass
statement is a "do-nothing" placeholder. In the case where you get an exception, the same cl
value will be tried again.
Of course, you will also want to add some mechanism where you can exit the loop if you always get an exception.
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