【问题标题】:Catch Exception in for Loop Python在 for Loop Python 中捕获异常
【发布时间】:2021-04-13 02:34:12
【问题描述】:

我有以下 for 循环:

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

在从加载程序中提取批次时,我的循环有时会失败。我想做的是类似于下面的 sn-p,但我希望能够在下一个值上继续循环,而不是跳过其余的值。

error_idxs = [] 

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

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

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

【问题讨论】:

  • 只需将 try/except 放在循环内而不是循环外
  • 如果加载器失败了你怎么能再问呢?那么什么时候停止呢?
  • 加载器失败后,可以再问一遍吗?很奇怪
  • 我正在尝试捕获代码循环部分中的错误。所以我的错误是在提取批次时发生的。

标签: python python-3.x exception try-catch


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

编辑:将StopIterationError 更正为StopIteration 并删除continue

【讨论】:

  • 我认为这可能会做到这一点。请问StopIterationError是干什么用的?
  • 如果迭代器的值用完,是否退出? @sunnytown
  • 是的,next 将在迭代器耗尽时引发 StopIteration 异常。
  • StopIteration 在可迭代对象(因此加载器)用完新值时引发。 for 循环在幕后自动捕获 StopIteration 并使用它来知道何时应该停止。 while 循环不会,因为它永远运行,因此我们必须自己抓住它。
  • 顺便说一句。如果您知道加载程序出现连接问题时引发的确切异常,那么我建议您将该错误写入而不是Exception。如果您不这样做,它将捕获所有可能的异常,这是您要避免的。
【解决方案2】:

您可以改用 while 循环。

在这里,它将在循环中提取,以便可以在循环中捕获异常并处理并继续休息!

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)

【讨论】:

    猜你喜欢
    • 2011-12-26
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多