Skip to Content
Course content

22: File I/O and Exceptions Revisited

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this bug a dozen times in production code, usually written by someone who knows how to use Ruby but hasn't yet been burned by a "resource leak." Let's look at a piece of code intended to process a list of user IDs from a text file and write the "processed" versions to a new file.

def process_user_ids(input_path, output_path)
  input = File.open(input_path, "r")
  output = File.open(output_path, "w")

  while line = input.gets
    id = line.strip
    # Imagine some complex validation logic here that might raise an error
    raise "Invalid ID format" if id.empty? 
    
    output.puts "USER_#{id}"
  end

  input.close
  output.close
end

At first glance, it looks fine. It opens the files, does the work, and closes them. But here is the problem: if that raise "Invalid ID format" ever triggers, the execution jumps straight out of the method. The input.close and output.close lines are never reached. In a small script, the OS will eventually clean this up. In a long-running Rails server or a background worker processing thousands of files, you'll eventually hit the "Too many open files" error, and your application will crash.

The Leak That Kills Your Server

The core issue is that we're managing the file lifecycle manually. When you call File.open without a block, you are taking full responsibility for that file handle. If an exception occurs anywhere between the open and the close, that handle stays open in memory. It's a classic leak.

Now, you could wrap everything in a begin...ensure block to make sure the files close no matter what happens. That works, but it's verbose and frankly, it's not the "Ruby way."

Letting Ruby Handle the Cleanup

The most elegant fix is to use the block form of File.open. When you pass a block to File.open, Ruby guarantees that the file will be closed as soon as the block terminates, regardless of whether it finished successfully or raised an exception. It's essentially a built-in ensure block.

def process_user_ids(input_path, output_path)
  File.open(input_path, "r") do |input|
    File.open(output_path, "w") do |output|
      while line = input.gets
        id = line.strip
        raise "Invalid ID format" if id.empty?
        output.puts "USER_#{id}"
      end
    end
  end
end

Notice how much cleaner this is. We don't need to call .close explicitly. Ruby handles the plumbing, and our code focuses on the logic. If an "Invalid ID format" error occurs, Ruby closes both file handles before propagating the exception up the stack.

Guarding Against the Unexpected

Closing the file is one half of the battle; the other half is handling the fact that the file system is an unreliable place. Files get deleted, permissions change, and disks fill up. If you call File.open on a file that doesn't exist, Ruby raises an Errno::ENOENT exception.

In a real application, you don't want your whole process to die just because one config file is missing. This is where we revisit exception handling. Instead of a generic rescue (which is a bad habit because it catches NoMemoryError or Interrupt), we should be surgical about what we catch.

def safe_process_users(input_path, output_path)
  process_user_ids(input_path, output_path)
rescue Errno::ENOENT => e
  puts "File not found: #{e.message}. Skipping processing."
rescue Errno::EACCES => e
  puts "Permission denied: #{e.message}. Please check file rights."
rescue StandardError => e
  puts "An unexpected error occurred: #{e.message}"
end

By catching Errno::ENOENT and Errno::EACCES specifically, we handle the "expected" failures of the file system while still letting truly catastrophic errors (like a syntax error in our code) crash the program so we can actually find and fix them.




📋 Practical Task

The Robust Log Error Extractor

Your task is to build a utility that extracts "ERROR" level entries from a system log file and writes them to a summary file. However, this utility must be "production-ready," meaning it cannot crash due to file system issues or malformed data.

Requirements:

  • Create a method extract_errors(log_path, summary_path).
  • Use block-form File.open for both reading and writing to prevent resource leaks.
  • The method should only write lines that start with the word "ERROR" to the summary file.
  • Implement specific rescue blocks to handle:
    • Errno::ENOENT: Print "Log file missing" and return false.
    • Errno::EACCES: Print "Permission denied" and return false.
  • If a line in the log file is not a string (e.g., if you were processing an array of mixed data) or causes a StandardError during processing, the program should log the error to the console but continue processing the rest of the file.
  • Return true if the process completed successfully.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.