StopIteration — Easy Examples
Raised by next() to signal that an iterator is exhausted
Triggering StopIteration
How StopIteration is raised and how to catch it.
python
# Triggering and catching StopIteration try: it = iter([]); next(it) except StopIteration as e: print(f"Caught StopIteration: {e}") print(f"Type: {type(e).__name__}")
StopIteration is raised when raised by next() to signal that an iterator is exhausted. Always catch specific exceptions rather than bare except clauses.
Handling StopIteration
Basic error handling pattern for StopIteration.
python
# Safe handling pattern def safe_operation(): try: it = iter([]); next(it) except StopIteration: print("Operation failed gracefully") return None result = safe_operation() print(f"Result: {result}")
Wrapping risky operations in try/except blocks prevents your program from crashing.
Want to try these examples interactively?
Open Easy Playground