python
runtime_error
ai_generated
true
停止迭代:
StopIteration:
ID: python/stopiteration-next-on-empty-generator
80%修复率
84%置信度
0证据数
2025-04-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
根因分析
在没有默认值的情况下对没有更多项的生成器或迭代器调用 next()。
English
Calling next() on a generator or iterator that has no more items, without a default value.
解决方案
-
95% 成功率 Provide default value to next()
item = next(generator, None)
-
90% 成功率 Use for loop instead of next()
for item in generator: process(item)
无效尝试
常见但无效的做法:
-
Catching StopIteration with a bare except
60% 失败
Bare except catches all exceptions, potentially hiding other bugs.
-
Using list(iterator) without checking length
40% 失败
list() consumes the iterator but does not handle empty case gracefully.