235

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?

4
  • 4
    Don't see how the accepted answer (use continue) catches exceptions, but it was accepted. Therefore, the question is really, really confusing.
    – S.Lott
    Feb 15, 2009 at 3:31
  • @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
    Feb 15, 2009 at 3:38
  • @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
    Feb 15, 2009 at 20:58
  • 1
    @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
    Feb 15, 2009 at 22:17

6 Answers 6

495

You are looking for continue.

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

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
22

Something like this?

for i in xrange( someBigNumber ):
    try:
        doSomethingThatMightFail()
    except SomeException, e:
        continue
    doSomethingWhenNothingFailed()
1
  • 1
    Edited to use continue rather than pass. Dec 3, 2012 at 12:25
17

I think you're looking for continue

9

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.