×

ruby · level 2 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

stops bad values with a clear message.

Your own methods can raise exceptions too. Check the values at the top of a method, and if one makes no sense, raise an error before anything else happens. A crash with a clear message beats a wrong answer nobody notices.

raise ArgumentError, "Buy at least one ticket" names the error and gives a message. raise "Out of stock", with only a message, raises a . Whoever calls the method can rescue it like any other error.

def tickets_cost(count)
  raise ArgumentError, "Buy at least one ticket" if count < 1
  count * 8
end
puts tickets_cost(3)
begin
  tickets_cost(0)
rescue ArgumentError => error
  puts "Error: #{error.message}"
end

Raise early, at the top of the method, before any real work is done.