198
votes

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?

6
Don't see how the accepted answer (use continue) catches exceptions, but it was accepted. Therefore, the question is really, really confusing. - S.Lott
@S.Lott I don't need the keyword to catch the exception, i was just talking about the general flow of the total code. - The.Anti.9
@The.Anti.9. What? First you said "I want to catch the exceptions". Now you're saying "I don't need the keyword to catch the exception". Could you clarify this in some way? - S.Lott
@S.Lott. I don't need to catch the exception with the keyword, there just has to be a try, except statement in the code.... - The.Anti.9
I reworded the question to make it better match the accepted answer. - jilles de wit

6 Answers

449
votes

You are looking for continue.

54
votes
for i in iterator:
    try:
        # Do something.
        pass
    except:
        # Continue to next iteration.
        continue
28
votes

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
18
votes

Something like this?

for i in xrange( someBigNumber ):
    try:
        doSomethingThatMightFail()
    except SomeException, e:
        continue
    doSomethingWhenNothingFailed()
15
votes

I think you're looking for continue

6
votes

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