我有一个循环,但有可能在循环内引发异常.这当然会一起阻止我的程序.为了防止我捕获异常并处理它们.但是,即使发生异常,迭代的其余部分也会运行.在我的except:
子句中是否有一个关键字可以跳过当前迭代的其余部分?
你正在寻找继续.
for i in iterator: try: # Do something. pass except: # Continue to next iteration. continue
像这样的东西?
for i in xrange( someBigNumber ): try: doSomethingThatMightFail() except SomeException, e: continue doSomethingWhenNothingFailed()
继续示例:
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..except..else
是最干净的解决方案,else
如果未引发异常,则将执行该子句。
注意:该else
子句必须跟在所有except
子句之后
for i in iterator: try: # Do something. except: # Handle exception else: # Continue doing something