← All languages
Ruby method of the day
Random

raise

Raise an exception to signal an error condition.

Description

The raise method creates and raises an exception, interrupting normal program flow. It can be called with a string message, an exception class, or an exception class with a message. Without arguments, it re-raises the current exception in a rescue block.

When called with just a string, raise creates a RuntimeError with that message. When called with an exception class and a message, it creates an instance of that class. You can also pass a backtrace array as a third argument.

Raised exceptions propagate up the call stack until they are caught by a matching rescue clause. If no rescue handles the exception, the program terminates. The alias fail can be used interchangeably with raise.

Arguments

NameDescriptionOptional
exception_or_message An exception class, exception instance, or string message. Yes
message An error message string when first argument is a class. Yes

Example

raise "Something went wrong"
# RuntimeError: Something went wrong

raise ArgumentError, "Invalid input"
# ArgumentError: Invalid input

begin
  raise "oops"
rescue => e
  puts e.message  # "oops"
end

Reference