Exception Classes / StandardError / RuntimeError
Ruby provides exception classes organized by purpose. You can also define and use your own custom exception classes.
Syntax
# Define a custom exception class.
class CustomError < StandardError
def initialize(msg = "Default message")
super
end
end
# Raise the custom exception.
raise CustomError
raise CustomError, "Detailed message"
raise CustomError.new("Message")
# Check the exception class hierarchy.
puts ErrorClass.ancestors
Common Exception Classes
| Exception Class | Description |
|---|---|
| StandardError | The base class for general errors. Custom exceptions inherit from this. |
| RuntimeError | The default exception raised when no class is specified with raise. |
| TypeError | Raised when a value has an invalid type (e.g., adding a string and an integer). |
| ArgumentError | Raised when the number or value of arguments is invalid. |
| NameError | Raised when referencing an undefined variable or method name. |
| NoMethodError | Raised when calling a method that does not exist (a subclass of NameError). |
| ZeroDivisionError | Raised when dividing an integer by zero. |
| IOError | Raised when a file or stream operation fails. |
| Errno::ENOENT | Raised when a file or directory cannot be found. |
Sample Code
# Define custom exception classes.
class ValidationError < StandardError
attr_reader :field_name
def initialize(field_name, msg = nil)
@field_name = field_name
super(msg || "#{field_name} has an invalid value.")
end
end
class AgeError < ValidationError; end
# Raise and rescue custom exceptions.
def register_user(name, age)
raise ValidationError.new("name"), "Name is required." if name.empty?
raise AgeError.new("age"), "Age must be 0 or greater." if age < 0
puts "Registered #{name} (age #{age})."
end
begin
register_user("Tanaka", 25)
register_user("", 20)
rescue AgeError => e
puts "Age error: #{e.message}"
rescue ValidationError => e
puts "Validation error [#{e.field_name}]: #{e.message}"
end
Overview
Ruby's exception classes form a hierarchy with Exception at the top. In most cases, you work with subclasses of StandardError, and custom exceptions should also inherit from StandardError.
Defining custom exception classes lets you clearly distinguish between error types, allowing callers to handle them appropriately. Writing rescue Exception also catches signals like SignalException and SystemExit, which prevents you from terminating the program with Ctrl+C. In general, use rescue StandardError or specify a particular subclass.
If you find any errors or copyright issues, please contact us.