×

ruby · level 2 · unit 5 · lesson 2

  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

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.