File Handling and Exception Handling in Ruby

March 2, 2024

This lesson will focus on file handling operations in Ruby, including reading from and writing to files. Additionally, it will cover exception handling to manage errors and unexpected behaviors in Ruby programs.

File Handling in Ruby

File handling is an essential part of programming, allowing you to work with external files to store and retrieve data. Ruby provides a simple and powerful way to perform file handling operations.

Opening and Closing Files

In Ruby, you can open a file using the File.open method. This method takes the file name and an optional mode as parameters. The modes include:

<pre><code>File.open('example.txt', 'r')  # Opens the file for reading
File.open('example.txt', 'w')  # Opens the file for writing
File.open('example.txt', 'a')  # Opens the file for appending
</code></pre>

After performing file operations, it’s crucial to close the file using the close method to release the resources.

Reading from Files

To read from a file in Ruby, you can use the File.read or File.readlines methods. The File.read method reads the entire content of the file into a string, while the File.readlines method reads the lines of the file into an array.

Writing to Files

Writing to a file in Ruby is achieved using the File.write method. This method takes the file name and the content to be written as parameters.

Exception Handling in Ruby

Exception handling is crucial for managing errors and unexpected behaviors in Ruby programs. It allows you to gracefully handle exceptions and prevent program crashes.

In Ruby, you can use the begin, rescue, and ensure keywords to handle exceptions. The begin block contains the code that might raise an exception, while the rescue block handles the exception and provides a fallback behavior. The ensure block ensures that certain code is always executed, regardless of whether an exception occurs.

Example of Exception Handling

<pre><code>begin
  # Code that might raise an exception
  result = 10 / 0
rescue ZeroDivisionError => e
  # Handle the ZeroDivisionError
  puts 'Error: Division by zero'
  result = 0
ensure
  # Ensure cleanup code
  puts 'Ensure block always executed'
end
</code></pre>

In the example above, the rescue block handles the ZeroDivisionError and provides a fallback behavior, preventing the program from crashing.

By understanding file handling and exception handling in Ruby, you can write robust and reliable programs that effectively manage external files and handle unexpected errors.