How to skip iterations in a loop?

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

You are looking for continue.

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

Something like this?

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

Solution 5 - Python

I think you're looking for continue

Solution 6 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe.Anti.9View Question on Stackoverflow
Solution 1 - PythonAndréView Answer on Stackoverflow
Solution 2 - PythonAlex McBrideView Answer on Stackoverflow
Solution 3 - PythonCode JView Answer on Stackoverflow
Solution 4 - PythonS.LottView Answer on Stackoverflow
Solution 5 - PythonJason PunyonView Answer on Stackoverflow
Solution 6 - PythonIstvan Jeno VeresView Answer on Stackoverflow