Custom Errors in Ruby
Our first example demonstrates how to create custom errors in Ruby. While Ruby doesn’t have a built-in error interface like some other languages, we can achieve similar functionality by creating our own error classes.
# A custom error class. It's common to use the suffix "Error" for custom errors.
class ArgError < StandardError
attr_reader :arg
def initialize(arg, message)
@arg = arg
super("#{arg} - #{message}")
end
end
def f(arg)
if arg == 42
# Raise our custom error
raise ArgError.new(arg, "can't work with it")
end
arg + 3
end
begin
f(42)
rescue ArgError => e
puts e.arg
puts e.message
else
puts "No ArgError was raised"
end
In this example, we define a custom ArgError
class that inherits from StandardError
. This class has an arg
attribute and a custom initialize
method that formats the error message.
The f
function raises our custom error when the argument is 42, similar to the original example.
In the main part of the script, we use a begin/rescue
block (Ruby’s equivalent to try/catch) to handle the error. If an ArgError
is raised, we can access its arg
attribute and message.
To run the program, save it as custom_errors.rb
and use the ruby
command:
$ ruby custom_errors.rb
42
42 - can't work with it
This output shows that our custom error was raised and caught successfully, and we were able to access both the arg
value and the full error message.
Ruby’s exception handling system is quite flexible, allowing you to create and use custom errors to provide more detailed information about what went wrong in your program.