Ruby Language Raising an exception


Example

To raise an exception use Kernel#raise passing the exception class and/or message:

raise StandardError # raises a StandardError.new
raise StandardError, "An error" # raises a StandardError.new("An error")

You can also simply pass an error message. In this case, the message is wrapped into a RuntimeError:

raise "An error" # raises a RuntimeError.new("An error")

Here's an example:

def hello(subject)
  raise ArgumentError, "`subject` is missing" if subject.to_s.empty?
  puts "Hello #{subject}"
end

hello # => ArgumentError: `subject` is missing
hello("Simone") # => "Hello Simone"