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.
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:
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.