ruby · level 2 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Which error is it? Guess the output.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class TooHot < StandardError; end
def check(temp)
raise TooHot, "Phew, #{temp} degrees" if temp > 30
"#{temp} degrees is lovely"
end
[18, 35].each do |temp|
puts check(temp)
rescue TooHot => error
puts "#{error.class}: #{error.message}"
end
your turn
Your turn. Guard the cinema door.
Name an error class for someone who is too young, in CamelCase. Use the same name in all three blanks.
fix it
Ruby will not raise this error. Can you fix it?
- Read the error. Ruby says
raisewas handed something that is not an exception. Look at line 1. - Your error class must be built on StandardError, or
raisewill not accept it. - Change line 1 to class NoSeats < StandardError; end, then press run.
nailed it
your errors have names of their own. :D
- Build your own errors on StandardError.
- Raise them with a message and rescue them by name.
- Other bugs still crash, so nothing gets hidden.
new words in your collection
- StandardError
This lesson isn’t saved. A free account remembers every lesson you finish.