How to skip iterations in a loop?

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?

5

6 Answers

You are looking for continue.

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

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 

Something like this?

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

I think you're looking for continue

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like