ruby · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Name the error you expect, and only that one is caught.
A bare rescue catches almost everything, even your typos, which hides bugs. Name the exception instead. catches dividing by 0 and lets other errors crash as usual, so you still hear about them.
.to_i turns "abc" into 0 without a word. Integer("abc") is stricter: it raises an . You can stack several rescue lines, one for each kind of error, and Ruby runs the first one that matches.
["12", "abc", "0"].each do |answer|
begin
puts 60 / Integer(answer)
rescue ArgumentError
puts "#{answer} is not a number"
rescue ZeroDivisionError
puts "Cannot divide by zero"
end
end A missing file raises Errno::ENOENT, and you can rescue that by name too.
guess first
Which rescue runs? Guess the output.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
begin
puts Integer("12")
puts Integer("twelve")
rescue ZeroDivisionError
puts "Zero!"
rescue ArgumentError => error
puts "Bad: #{error.message}"
end
your turn
Your turn. Check the ticket orders.
Fill in two answers, one in digits and one that is not a number. In the last blank, write the error that Integer raises.
fix it
A typo is hiding behind the rescue. Can you fix it?
- "5" is a number, yet it says it is not. Something else is going wrong, and the bare
rescueis hiding it. - Change
rescuetorescue ArgumentErrorand run it. The real error, a NameError, will show itself. - The variable on line 3 is misspelt. Change answr to answer, then press run.
nailed it
you catch exactly the right error. :D
rescue ZeroDivisionErrorcatches only that one kind of error.Integer("abc")raises an ArgumentError instead of giving 0.- A bare
rescuecan hide your own typos.
new words in your collection
- ZeroDivisionError
- ArgumentError
This lesson isn’t saved. A free account remembers every lesson you finish.