Python for 循环中捕获异常

A M*_*rii 3 python exception try-catch python-3.x

我有以下 for 循环:

for batch in loader:
    # do something with batch
    ...
Run Code Online (Sandbox Code Playgroud)

从加载器中提取批处理时,我的循环有时会失败。我想做的是类似于下面的代码片段,但我希望能够继续循环下一个值,而不是跳过其余的值。

error_idxs = [] 

try:
    for i,batch in enumerate(loader):
        # do something with batch
        ...
except:
    error_idxs.append(i)
Run Code Online (Sandbox Code Playgroud)

上述方法的问题在于,一旦发生异常,它就会退出循环,而不是继续下一个批次。

有没有办法在下一批中继续循环?

sun*_*own 5

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

编辑:更正StopIterationErrorStopIteration删除continue

  • 顺便提一句。如果您知道加载程序出现连接问题时引发的确切异常,那么我建议您将该错误写入而不是“Exception”。如果你不这样做,它将捕获所有可能的异常,这是你想要避免的。 (2认同)