Kernel#raise
raise([exception [, msg [, backtrace]]]) -> nil Returns:
nil or the raised exception · Updated March 13, 2026 · Kernel Methods exceptions errors control-flow
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.
Syntax
raise
raise message
raise ExceptionClass
raise ExceptionClass, message
raise ExceptionClass, message, backtrace
Parameters
| Parameter | Description |
|---|---|
| exception | Optional. An exception class (e.g., RuntimeError, ArgumentError) or an instance of an exception. Defaults to RuntimeError when omitted. |
| message | Optional. A string describing the error. Defaults to “x” for RuntimeError or the exception’s default message. |
| backtrace | Optional. A custom backtrace array (typically from caller). |
Examples
Basic Usage
raise "Something went wrong"
# => (raises RuntimeError with message "Something went wrong")
Raising a Specific Exception Type
raise ArgumentError, "Invalid argument provided"
# => (raises ArgumentError: Invalid argument provided)
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
Conditional Error Handling
def withdraw(amount)
balance = 100
if amount > balance
raise "Insufficient funds"
end
balance - amount
end
withdraw(150)
# => raises: RuntimeError: Insufficient funds
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
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
Custom Exception Classes
class ValidationError < StandardError; end
def validate!(input)
raise ValidationError, "Input cannot be empty" if input.nil? || input.empty?
end
Errors (Common Exception Types)
| Exception | Description |
|---|---|
RuntimeError | Generic error raised when no specific class is specified (default) |
ArgumentError | Raised when method arguments are invalid |
TypeError | Raised when an object is of the wrong type |
NoMethodError | Raised when calling a method that doesn’t exist |
StandardError | Base class for most user-defined exceptions |
ZeroDivisionError | Raised when attempting to divide by zero |