RuntimeError: Generator Raised StopIteration

RuntimeError: generator raised StopIteration

Quick Answer

A StopIteration was raised inside a generator, which Python 3.7+ converts to RuntimeError. Use return instead of raise StopIteration, or catch StopIteration inside the generator.

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 generator

Step-by-Step Fix

  1. 1

    Use return instead

    End generators with return, not raise StopIteration.

  2. 2

    Catch StopIteration

    Wrap next() calls in try/except inside generators.

  3. 3

    Use yield from

    Use 'yield from iterable' to delegate to another iterator.

Bugsly 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