简体   繁体   English

在 for 循环 Python 中捕获异常

[英]Catch Exception in for Loop Python

I have the below for loop:我有以下for循环:

for batch in loader:
    # do something with batch
    ...

My loop sometimes fails, while extracting the batch from the loader.从加载程序中提取批次时,我的循环有时会失败。 What I want to do is something similar to snippet below, but I would like to be able to continue the loop on the next value, rather than skip the rest of the values.我想做的是类似于下面的代码片段,但我希望能够在下一个值上继续循环,而不是跳过值的 rest。

error_idxs = [] 

try:
    for i,batch in enumerate(loader):
        # do something with batch
        ...
except:
    error_idxs.append(i)

The problem with the method above is that it exits out of the loop as soon as an exception happens rather than continuing with the next batch.上述方法的问题在于,一旦发生异常,它就会退出循环,而不是继续下一批。

Is there a way to continue looping at the next batch?有没有办法在下一批继续循环?

error_idxs = []
i = 0
while True:
    try:
        batch = next(loader)
        # do something
    except StopIteration:
        break
    except Exception:
        error_idxs.append(i)
    finally:
        i += 1

Edit: Corrected StopIterationError to StopIteration and removed continue编辑:将StopIteration StopIterationError删除continue

You may use while loop instead.您可以改用 while 循环。

Here it will be extracted inside loop so exception can be caught inside loop and handled and continued with rest!在这里,它将在循环内提取,因此可以在循环内捕获异常并处理并继续休息!

error_idxs = [] 

i = -1
while i < len(loader) -1:
    try:
        i = i + 1
        batch = loader[i]
        do something witth batch
        ...
    except:
        error_idxs.append(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM