๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Rescue Patterns

A rescue line can name the exact error class it catches. Naming the class keeps one kind of failure from hiding another.

Rescue naming one class

Dividing by zero raises a ZeroDivisionError. The rescue line names that class, so it catches the error and prints a line.

begin
  result = 10 / 0
  puts result
rescue ZeroDivisionError
  puts "Cannot divide by zero"
end

Two rescue lines in one block

The block holds a rescue line for each failure it expects. Ruby checks the lines in order and runs the one that matches.

begin
  total = 10 / 0
  puts total
rescue TypeError
  puts "Wrong type"
rescue ZeroDivisionError
  puts "Divided by zero"
end

The else line when nothing fails

The division works, so no rescue line runs. The else line runs instead and prints both lines.

begin
  total = 6 / 2
rescue ZeroDivisionError
  puts "Divided by zero"
else
  puts "No error happened"
  puts total
end

Reading e.class and e.message

The first block prints the class of a caught error. The second block raises its own fixed message, and the rescue prints that message.

begin
  result = 1 / 0
  puts result
rescue ZeroDivisionError => e
  puts e.class
end
begin
  raise "Stock is empty"
rescue => e
  puts e.message
end

Example

price = 100
count = 0
begin
  each_price = price / count
  puts each_price
rescue ZeroDivisionError => e
  puts e.class
  puts "Add items first"
else
  puts "Done"
end

Key points

  • rescue with a class name catches only errors of that class.
  • A plain rescue catches the standard errors a beginner program meets.
  • Two rescue lines can sit in one begin block.
  • Ruby tries the rescue lines from top to bottom.
  • The else line runs only when no error was raised.
  • e.class names the class of the error that was caught.
  • e.message gives the message text the error carries.

In this example, dividing the price by a count of zero raises a ZeroDivisionError. The rescue line names that class and catches the error into e. The block prints the class name from e.class, then prints its own line, and the else line stays silent.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A begin block finishes with no error. The block has a rescue line and an else line, and each holds one puts line. Which line prints?