Reputation: 44648
I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that, I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my except:
clause to just skip the rest of the current iteration?
Upvotes: 254
Views: 457097
Reputation: 1214
Example for Continue:
number = 0
for number in range(10):
number = number + 1
if number == 5:
continue # continue here
print('Number is ' + str(number))
print('Out of loop')
Output:
Number is 1
Number is 2
Number is 3
Number is 4
Number is 6 # Note: 5 is skipped!!
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop
Upvotes: 61
Reputation: 91
For this specific use-case using try..except..else
is the cleanest solution, the else
clause will be executed if no exception was raised.
NOTE: The else
clause must follow all except
clauses
for i in iterator:
try:
# Do something.
except:
# Handle exception
else:
# Continue doing something
Upvotes: 9
Reputation: 391820
Something like this?
for i in xrange( someBigNumber ):
try:
doSomethingThatMightFail()
except SomeException, e:
continue
doSomethingWhenNothingFailed()
Upvotes: 23
Reputation: 7011
for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
Upvotes: 69