Errors and Files
begin/rescue/ensure handles errors. File.write and File.read store text, and File.foreach reads line by line.
Example
begin
Integer("abc")
rescue ArgumentError => e
puts "Bad number: #{e.message}"
ensure
puts "done"
end
path = "/tmp/ruby_demo.txt"
File.write(path, "one\ntwo\n")
File.foreach(path) { |l| puts l.chomp.upcase }
File.delete(path)Result
Bad number: invalid value for Integer(): "abc" done ONE TWO
Exercise
Handle an error.
begin rescue end
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.