rubyguides

Kernel#raise

raise([exception [, msg [, backtrace]]]) -> nil

raise is a Kernel method that triggers an exception, interrupting the normal program flow. When an exception is raised, Ruby searches up the call stack for a rescue block that can handle it. If no handler is found, the program terminates and displays the exception message along with a backtrace. This mechanism is fundamental to Ruby’s error handling and is used for everything from validating input to handling unexpected runtime conditions.

The examples below move from the simplest form to custom exception classes. That progression makes it easier to see how much control raise gives you over both the message and the exception type.

Syntax

raise
raise message
raise ExceptionClass
raise ExceptionClass, message
raise ExceptionClass, message, backtrace

Parameters

ParameterDescription
exceptionOptional. An exception class (e.g., RuntimeError, ArgumentError) or an instance of an exception. Defaults to RuntimeError when omitted.
messageOptional. A string describing the error. Defaults to “x” for RuntimeError or the exception’s default message.
backtraceOptional. A custom backtrace array (typically from caller).

Examples

Basic Usage

raise "Something went wrong"
# => (raises RuntimeError with message "Something went wrong")

The simplest form of raise takes a single string and creates a RuntimeError with that message. This is enough for quick scripts and early prototypes where the error type does not matter to the caller — the message alone carries the signal. In production code, using a specific exception class is usually a better choice because it gives rescue blocks a precise class to match against instead of catching RuntimeError broadly.

raising a specific exception type

raise ArgumentError, "Invalid argument provided"
# => (raises ArgumentError: Invalid argument provided)

Picking a specific exception class helps callers rescue the right kind of failure. It also gives the error more meaning than a generic runtime exception, especially when the method is part of a larger API or a public service boundary where the caller needs to distinguish one error from another.

using raise in a method

def divide(a, b)
  raise ZeroDivisionError, "Cannot divide by zero" if b == 0
  a / b
end

divide(10, 0)
# => raises: ZeroDivisionError: Cannot divide by zero

This version keeps the validation close to the rule being enforced. The method fails fast, and the error message explains exactly why the call is invalid instead of forcing the caller to guess. Combining the guard clause and the raise on a single line with a trailing if is a common Ruby idiom for argument checking.

conditional error handling

def withdraw(amount)
  balance = 100
  if amount > balance
    raise "Insufficient funds"
  end
  balance - amount
end

withdraw(150)
# => raises: RuntimeError: Insufficient funds

The generic string form is fine when the surrounding code only needs a quick failure signal. If the error should be rescued selectively, switching to a named exception class is usually the better choice. The method call itself stays compact, and the class name carries the error category without extra documentation.

common patterns

validation pattern

def set_age(age)
  raise ArgumentError, "Age must be a number" unless age.is_a?(Numeric)
  raise ArgumentError, "Age cannot be negative" if age < 0
  @age = age
end

Validation raises are most useful when they appear right beside the rule they enforce. The caller sees the guard clause immediately, and the method stays easy to read because the happy path is not buried under extra branching. Stacking multiple guard clauses with specific exception types gives each failure case its own class and message, which makes debugging faster when a bad input arrives.

re-raising exceptions

begin
  # Some operation that might fail
  File.read("nonexistent.txt")
rescue => e
  puts "Error occurred: #{e.message}"
  raise  # Re-raises the same exception
end

Re-raising is handy when you need to log or annotate the failure before letting it continue upward. The key is to avoid swallowing the original exception unless you are replacing it with something more specific. A bare raise inside a rescue block passes the same exception up the call stack unchanged.

custom exception classes

class ValidationError < StandardError; end

def validate!(input)
  raise ValidationError, "Input cannot be empty" if input.nil? || input.empty?
end

Custom exception classes make larger codebases easier to work with because they let callers rescue one failure type without matching on message text. That is especially useful when a single service method can fail for several different reasons.

errors (common exception types)

ExceptionDescription
RuntimeErrorGeneric error raised when no specific class is specified (default)
ArgumentErrorRaised when method arguments are invalid
TypeErrorRaised when an object is of the wrong type
NoMethodErrorRaised when calling a method that doesn’t exist
StandardErrorBase class for most user-defined exceptions
ZeroDivisionErrorRaised when attempting to divide by zero

Kernel#raise is most useful when the problem should stop the current path and be handled somewhere else. That makes it a natural fit for validation, boundary checks, and truly unexpected conditions. The exception class and message should say enough for the next reader to understand what went wrong without needing to inspect the whole call stack. A short, specific exception is usually easier to support than a vague one.

It also helps to keep the raise near the rule it enforces. When the condition and the exception sit side by side, the code reads like a direct statement of the program’s expectations. That makes the behavior easier to test and the failure mode easier to explain when the input is bad.

See Also