×

ruby · level 2 · unit 7 · lesson 1

  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

Your own error classes name your program's problems.

Errors are objects too, and every error has a class: ArgumentError, ZeroDivisionError and the rest. Most of them are subclasses of . Make your own the same way, with class OutOfStock < StandardError. It needs nothing inside.

Raise it with a message, like any other error. The caller can rescue OutOfStock by name, while typos and other bugs still crash loudly, so nothing gets hidden. A bare rescue catches any StandardError, yours included.

class OutOfStock < StandardError; end
def sell(stock)
  raise OutOfStock, "No cakes left" if stock == 0
  "Sold one, #{stock - 1} left"
end
[2, 0].each do |stock|
  puts sell(stock)
rescue OutOfStock => error
  puts "Sorry! #{error.message}"
end

An empty class fits on one line if a semicolon stands in for the line break before end.