我有循环,但是循环内部可能会引发异常。这当然会一起阻止我的程序。为了防止我捕获异常并处理它们。但是,即使发生异常,迭代的其余部分也会运行。我的except:
子句中是否有一个关键字可以跳过当前迭代的其余部分?
答案 0 :(得分:298)
您正在寻找continue。
答案 1 :(得分:44)
for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
答案 2 :(得分:16)
这样的东西?
for i in xrange( someBigNumber ):
try:
doSomethingThatMightFail()
except SomeException, e:
continue
doSomethingWhenNothingFailed()
答案 3 :(得分:11)
我认为你正在寻找continue
答案 4 :(得分:11)
继续示例:
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')
<强>输出:强>
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
答案 5 :(得分:3)
对于这个特定用例,使用try..except..else
是最干净的解决方案,如果没有引发异常,将执行else
子句。
注意:else
子句必须遵循所有except
条款
for i in iterator:
try:
# Do something.
except:
# Handle exception
else:
# Continue doing something