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
  1. 1Calling IO#readlines or IO#read on an empty or fully-consumed stream
  2. 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
end

Why 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 reached
Safe iteration with foreachruby
IO.foreach('data.txt') { |line| puts line }
# stops at EOF, no error
Rescue EOFErrorruby
begin
  loop { puts socket.readline }
rescue EOFError
  puts 'Connection closed by remote'
end
Sources
Official documentation ↗

Ruby Core Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors