Ruby - Handle Custom Exceptions using rescue

1. Introduction

Ruby offers an extensive system for handling exceptions, allowing developers to gracefully manage unexpected events in their code. While the language provides a set of predefined exceptions, there are cases where custom exceptions might be more suitable for the specific needs of an application. In this article, we will walk through the process of creating and handling custom exceptions using the rescue construct in Ruby.

What are Custom Exceptions?

Custom exceptions in Ruby are user-defined classes that inherit from the standard Exception class or its descendants. They allow for more specific error categorization and handling, tailored to the unique needs of a particular application.

2. Program Steps

1. Define a custom exception class by inheriting from the standard Exception class or its descendants.

2. Raise the custom exception using the raise keyword in situations where it is appropriate.

3. Use the begin...rescue construct to handle the custom exception gracefully.

4. Display a message or take appropriate action when the custom exception is encountered.

3. Code Program

# Define a custom exception
class AgeBelowMinimumError < StandardError; end
def check_age(age)
  # Raise the custom exception if age is below 18
  raise AgeBelowMinimumError, "Age should be 18 or above!" if age < 18
  puts "Age is appropriate."
end
# Using begin...rescue to handle the custom exception
begin
  check_age(15)
rescue AgeBelowMinimumError => e
  puts "Custom Exception: #{e.message}"
end

Output:

Custom Exception: Age should be 18 or above!

Explanation:

1. class AgeBelowMinimumError < StandardError; end: Here, we define a custom exception named AgeBelowMinimumError that inherits from the StandardError class.

2. def check_age(age): This is a method that checks if the age is below the specified minimum.

3. raise AgeBelowMinimumError, "Age should be 18 or above!" if age < 18: In the method, we raise our custom exception with a message when the age is below 18.

4. begin...rescue AgeBelowMinimumError => e: We use the begin...rescue construct to handle our custom exception. The => e part captures the exception object which allows us to access its message or other attributes.

5. puts "Custom Exception: #{e.message}": In the rescue block, we print the message associated with our custom exception.

By using custom exceptions, developers can create more expressive and precise error messages that better describe the specific conditions or validations in the code.


Comments