Ruby - Handle Multiple Exceptions Using Multiple rescue Blocks

1. Introduction

While programming, there's always the possibility of encountering various unexpected errors or exceptions. Ruby provides a robust mechanism to handle such exceptions using the rescue construct. For scenarios where multiple types of exceptions might occur, Ruby allows the use of multiple rescue blocks to handle each exception type individually. In this post, we'll delve into how to handle multiple exceptions using multiple rescue blocks.

In Ruby, begin...rescue is a construct that allows for the capturing and handling of exceptions. When multiple rescue blocks are used within a single begin...end construct, it enables the program to handle different types of exceptions in various ways, ensuring that each exception type is addressed appropriately.

2. Program Steps

1. Begin the potentially exception-causing code within a begin block.

2. Use rescue blocks to catch specific exception types.

3. Handle each exception type individually within its corresponding rescue block.

4. Optionally, provide an else block to execute code when no exceptions occur.

5. End the construct with the end keyword.

3. Code Program

# Define a method that might raise multiple exceptions
def divide(numerator, denominator)
  # Attempt to perform a division
  result = numerator / denominator
  # Handle possible zero division
rescue ZeroDivisionError
  puts "Cannot divide by zero!"
  # Handle possible type errors
rescue TypeError
  puts "Both arguments should be numbers!"
  # Code to be executed if no exceptions are raised
else
  puts "Result of the division is #{result}"
end
# Test the method with various inputs
divide(10, 2)
divide(10, 0)
divide('10', 2)

Output:

Result of the division is 5
Cannot divide by zero!
Both arguments should be numbers!

Explanation:

1. def divide(numerator, denominator): This method is designed to demonstrate a division operation that might raise multiple exceptions.

2. result = numerator / denominator: This line attempts to perform division and might raise either a ZeroDivisionError if denominator is 0 or a TypeError if any of the arguments isn't a number.

3. rescue ZeroDivisionError: This rescue block captures the ZeroDivisionError and prints a message indicating the error.

4. rescue TypeError: Similarly, this rescue block handles the TypeError by printing an appropriate message.

5. else: The else block contains code that will be executed if no exceptions are raised within the begin block.

6. divide(10, 2), divide(10, 0), divide('10', 2): These lines test the method with various inputs to trigger the different exception handlers.

Using multiple rescue blocks provides a clear structure to handle different exceptions individually, making the error handling process more granular and precise.


Comments