EOFError
RubyWARNINGCriticalIO
End of file reached unexpectedly
Quick Answer
Use IO#gets or IO.foreach which return nil at EOF instead of raising, or rescue EOFError to handle it gracefully.
What this means
Raised by IO#read and similar methods when the end of the file or stream is reached unexpectedly. EOFError is a subclass of IOError.
Why it happens
- 1Calling IO#readlines or IO#read on an empty or fully-consumed stream
- 2Network stream closing before all expected data is received
Fix
Use readline with rescue or check eof?
Use readline with rescue or check eof?
File.open('data.txt') do |f|
until f.eof?
line = f.readline
process(line)
end
endWhy this works
Checking eof? before each readline prevents the error from being raised.
Code examples
readline at EOFruby
f = StringIO.new('')
f.readline
# EOFError: end of file reachedSafe iteration with foreachruby
IO.foreach('data.txt') { |line| puts line }
# stops at EOF, no errorRescue EOFErrorruby
begin
loop { puts socket.readline }
rescue EOFError
puts 'Connection closed by remote'
endSame 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