Ruby Exceptions
An exception is an error a program can catch while it runs. A begin block and a rescue block catch the error so the program can carry on.
Catching a divide by zero
This program divides 10 by 0 inside a begin block. The rescue block prints a message instead of letting the program stop.
begin
puts 10 / 0
rescue
puts "Cannot divide by zero"
end
puts "The program continues"Raising an error with a message
raise makes an error with the message Age cannot be negative. The rescue line saves the error in e so the message can print.
begin
raise "Age cannot be negative"
rescue => e
puts e.message
end
puts "The program continues"When nothing goes wrong
This program divides inside a begin block and the division works. The rescue block is skipped and the normal lines print.
begin
puts 10 / 2
rescue
puts "Cannot divide by zero"
end
puts "No error happened"Example
begin
puts 10 / 0
rescue
puts "Cannot divide by zero"
end
begin
raise "Age cannot be negative"
rescue => e
puts e.message
end
puts "The program ends well"Key points
- Use begin to start a block of code that may fail.
- Use rescue to hold the code that runs when that block fails.
- A rescue block catches the error and the program continues after end.
- Use raise to make an error with a message.
- Use rescue => e to save the caught error in the name e.
- e.message gives the message the error carries.
In this example, the first begin block tries 10 / 0 and the division fails. Its rescue block prints Cannot divide by zero. The second begin block raises an error and rescue prints the message it carries. The last line prints because rescue kept the program running.
Note
An ensure block runs after the begin block whether an error happened or not.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens after a rescue block finishes?