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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You are looking for continue.
回答2:
for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
回答3:
Something like this?
for i in xrange( someBigNumber ):
try:
doSomethingThatMightFail()
except SomeException, e:
continue
doSomethingWhenNothingFailed()
回答4:
I think you're looking for continue
回答5:
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
回答6:
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