问题:在Python中跳过迭代

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

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?


回答 0

您正在寻找继续


回答 1

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

回答 2

像这样吗

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

Something like this?

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

回答 3

继续示例:

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

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

回答 4

我认为您正在寻找继续

I think you’re looking for continue


回答 5

对于此特定用例,使用try..except..else是最干净的解决方案,else如果未引发异常,则将执行该子句。

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

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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。