liveBook · Manning

Rescue block

As explained in The Well-Grounded Rubyist, Fourth Edition

A begin/rescue clause is Ruby exception-handling syntax that executes rescue code when a matching exception is raised.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains control transfer, exception specificity, implicit scopes, and narrower protected regions, but does not cover ensure or retry.
Examples
Uses zero-division input handling, file-opening methods, file-reading blocks, and a threaded TCP chat server.
What it assumes
Assumes familiarity with Ruby methods, blocks, exceptions, and basic control flow while demonstrating rescue syntax from concrete examples.
What you can do after
Builds exception handlers that select exception types and scope cleanup or recovery around failing operations.
How it connects
Connects exceptions with begin/end, methods, code blocks, threads, sockets, StandardError, and EOFError.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.