StopIteration
RubyINFOCriticalIteration
External iterator has no more values
Quick Answer
Use loop{} with an enumerator — it automatically rescues StopIteration to terminate cleanly.
What this means
Raised by Enumerator#next when there are no more elements. Unlike most exceptions, StopIteration is used as flow control for external iterators and is caught internally by loop{}.
Why it happens
- 1Calling Enumerator#next after all elements have been exhausted
- 2Manual external iteration without a termination check
Fix
Use loop to automatically handle StopIteration
Use loop to automatically handle StopIteration
enum = [1, 2, 3].each loop do puts enum.next end # prints 1, 2, 3 then exits cleanly
Why this works
Kernel#loop rescues StopIteration internally and breaks out of the loop when the enumerator is exhausted.
Code examples
Manual next raises StopIterationruby
e = [1, 2].each e.next # => 1 e.next # => 2 e.next # StopIteration: iteration reached an end
loop handles it automaticallyruby
loop { puts [1,2].each.next } # loops safelyClosedQueueError subclassruby
q = Queue.new q.close q.next rescue ClosedQueueError # subclass of StopIteration
Same error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev