Ruby - Create Custom Exception Class

1. Introduction

Exception handling is a crucial aspect of any robust software. While Ruby provides a variety of built-in exception classes, there are times when creating custom exceptions can enhance clarity and maintainability. In this post, we will delve into how to create and utilize custom exception classes in Ruby.


Custom exception classes in Ruby are user-defined classes that inherit from the built-in StandardError class (or one of its descendants). These custom classes can be tailored to represent specific error conditions within an application. By using custom exception classes, developers can convey more meaningful information about the type of error that occurred, as well as handle specific errors more precisely.

2. Program Steps

1. Define a custom exception class that inherits from StandardError.

2. Raise the custom exception in response to a specific error condition.

3. Handle the custom exception using a begin-rescue block.

3. Code Program

# Define a custom exception class
class InvalidAgeError < StandardError; end
def verify_age(age)
  # Raise the custom exception if age is negative
  raise InvalidAgeError, "Age cannot be negative!" if age < 0
  puts "Age is #{age}."
# Demonstrate how to handle the custom exception
rescue InvalidAgeError => e
  puts "Caught an error: #{e.message}"


Caught an error: Age cannot be negative!


1. We start by defining a custom exception class InvalidAgeError that inherits from Ruby's StandardError class. This inheritance ensures our custom exception can be used in the same way as built-in exceptions.

2. The verify_age method checks the provided age. If the age is negative, we raise our custom InvalidAgeError exception with a relevant error message.

3. In the demonstration part, we utilize a begin-rescue block to handle the potential InvalidAgeError. If this error is raised within the begin block, the corresponding rescue block captures it. The => e syntax allows us to reference the raised exception instance, enabling us to print its message.

4. Custom exception classes, like InvalidAgeError, enhance the clarity of the code by providing context-specific information about the type of error that has occurred. When other developers see or handle this exception, they can immediately understand the nature of the error without needing to decipher generic error messages.

Using custom exception classes is a valuable tool for creating expressive and maintainable Ruby applications. They allow developers to precisely indicate and handle various error conditions specific to the application's domain.