ruby · level 2 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Raise and rescue. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def withdraw(balance, amount)
raise "Not enough money" if amount > balance
balance - amount
end
begin
puts withdraw(50, 20)
puts withdraw(50, 80)
rescue => error
puts "#{error.class}: #{error.message}"
end
your turn
Your turn. Guard the lift.
The lift takes up to 300kg. Fill in two loads in kilograms to test it: one under the limit and one over.
fix it
The lemonade stand refuses every sale. Fix it!
- Read the error. The stand has 10 cups and you want 3, so why did it raise?
- The check on line 2 is back to front. It should only raise when someone wants more cups than are left.
- Change cups < stock to cups > stock on line 2, then press run.
nailed it
you stop bad values at the door. :D
raise ArgumentError, "message"stops with a named error.raise "message"on its own gives a RuntimeError.- Check values at the top of a method, before the work.
new words in your collection
- raise
- RuntimeError
This lesson isn’t saved. A free account remembers every lesson you finish.