Why This Happens
In Python 3.7+, StopIteration propagating out of a generator is converted to RuntimeError to prevent silent bugs. Use return to end a generator, not raise StopIteration.
The Problem
def my_gen(items):
it = iter(items)
while True:
yield next(it) # StopIteration escapes!The Fix
def my_gen(items):
it = iter(items)
while True:
try:
yield next(it)
except StopIteration:
return # Use return to end generatorStep-by-Step Fix
- 1
Use return instead
End generators with return, not raise StopIteration.
- 2
Catch StopIteration
Wrap next() calls in try/except inside generators.
- 3
Use yield from
Use 'yield from iterable' to delegate to another iterator.
Got the actual stack trace?
Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.
Explain my errorBugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free