0
0
Rubyprogramming~5 mins

Custom exception classes in Ruby

Choose your learning style9 modes available
Introduction

Custom exception classes help you create your own error types. This makes your program clearer and easier to fix when something goes wrong.

When you want to signal a specific problem in your program that built-in errors don't cover.
When you want to handle different errors in different ways.
When you want to add extra information to an error.
When you want your error messages to be clearer for users or developers.
Syntax
Ruby
class MyError < StandardError
  def initialize(msg = "My custom error happened")
    super(msg)
  end
end

Custom exceptions usually inherit from StandardError to fit well with Ruby's error handling.

You can add your own methods or data to the custom error class if needed.

Examples
A simple custom error class that inherits from StandardError.
Ruby
class MyError < StandardError
end
Custom error with a default message you can change when raising it.
Ruby
class MyError < StandardError
  def initialize(msg = "Something went wrong")
    super(msg)
  end
end
Custom error that stores an extra code value for more details.
Ruby
class MyError < StandardError
  attr_reader :code
  def initialize(msg = "Error", code = 100)
    @code = code
    super(msg)
  end
end
Sample Program

This program defines a custom error MyError. It raises this error if the input value is not positive. The error is caught and its message is printed.

Ruby
class MyError < StandardError
  def initialize(msg = "Custom error happened")
    super(msg)
  end
end

def test_error(value)
  raise MyError, "Value must be positive" if value <= 0
  "Value is #{value}"
end

begin
  puts test_error(-1)
rescue MyError => e
  puts "Caught a custom error: #{e.message}"
end
OutputSuccess
Important Notes

Always inherit from StandardError unless you have a special reason.

Use raise to trigger your custom error with a message.

Catch your custom errors with rescue YourErrorClass => e to handle them.

Summary

Custom exception classes let you create clear, specific errors for your program.

They help separate different error types for better handling.

Use inheritance from StandardError and add messages or extra info as needed.