A rescue block lets a Ruby program handle an exception instead of terminating immediately. Place the potentially failing code before a rescue clause inside begin/end; if a matching exception is raised, control jumps to the rescue code. If no exception occurs, Ruby skips the rescue clause and continues after end. section 6.4.2
Use rescue blocks with these distinctions in mind:
- A bare rescue handles exceptions descended from StandardError, while rescue ZeroDivisionError limits handling to that exception type. section 6.4.2
- Specific rescue clauses reduce the chance of hiding unrelated programming problems. section 6.4.2
- Methods and do/end blocks supply an implicit begin/end context, so rescue can govern the whole method or block without an explicit begin. section 6.4.2
- Add an explicit begin/end inside a method when only a smaller region should be protected, leaving later operations outside the rescue scope. section 6.4.2
Handling a departing chat client
A threaded chat server wraps its message-reading loop in begin/rescue. Each readline call normally broadcasts the received line; when a departing socket raises EOFError, the rescue block closes the socket, removes it from the active chatters, and announces the departure. section 14.5.3
print "Enter a number: "
n = gets.to_i
begin
result = 100 / n
rescue
puts "Your number didn't work. Was it zero???"
exit
end
puts "100/#{n} is #{result}."
Run this small interaction to see a failed division transfer control to rescue while successful division continues afterward. section 6.4.2
