Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. Exception Classes / StandardError / RuntimeError

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 ClassDescription
StandardErrorThe base class for general errors. Custom exceptions inherit from this.
RuntimeErrorThe default exception raised when no class is specified with raise.
TypeErrorRaised when a value has an invalid type (e.g., adding a string and an integer).
ArgumentErrorRaised when the number or value of arguments is invalid.
NameErrorRaised when referencing an undefined variable or method name.
NoMethodErrorRaised when calling a method that does not exist (a subclass of NameError).
ZeroDivisionErrorRaised when dividing an integer by zero.
IOErrorRaised when a file or stream operation fails.
Errno::ENOENTRaised 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 .