我有一个循环,但有可能在循环内部引发异常。这当然会使我的程序完全停止。为了防止这种情况,我捕获异常并处理它们。但是,即使出现异常,迭代的其余部分也会继续运行。在我的except:子句中是否有一个关键字可以跳过当前迭代的其余部分?


当前回答

for i in iterator:
    try:
        # Do something.
        pass
    except:
        # Continue to next iteration.
        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')

输出:

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

对于这个特定的用例,使用try..Else是最干净的解决方案,如果没有引发异常,Else子句将被执行。

注意:else子句必须跟在所有except子句后面

for i in iterator:
    try:
        # Do something.
    except:
        # Handle exception
    else:
        # Continue doing something

您正在寻找继续。

像这样的东西?

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