Exceptions and rescue

Exceptions and rescue in Ruby: --- Every floor of an old mill has a pull station on the wall: a small cast-iron box with a handle and the words BREAK GLASS.


The Analogy: The Fire Alarm Pull Station And The Zone Panel

Every floor of an old mill has a pull station on the wall: a small cast-iron box with a handle and the words BREAK GLASS. Pulling the handle does not put out a fire. It does exactly one thing -- it stops normal work everywhere and hands control to the gatehouse. Nobody on the third floor decides what happens next. The handle is a way of saying "I cannot deal with this, and I am not going to pretend the shift is still running."

In the gatehouse there is a zone panel: a board of labelled lamps, one per zone. Zone 3 is the paint store, zone 7 is the boiler room, zone 1 is the loading bay. The operator does not receive "a fire". They receive a zone, and they act on the zone: paint store means evacuate the wing and call the borough; boiler room means send the fitter with a wrench. The panel is what turns an undifferentiated emergency into a decision. Without it the operator would know only that something, somewhere, is wrong.

If nobody is at the panel, the alarm does not stop. It propagates outward -- to the borough fire service, and the whole building is emptied on their terms rather than yours. That is the correct default. An alarm nobody handles must reach someone who will, and it must arrive with the zone attached. Alongside all of this runs the sprinkler stop valve, which has to be closed at the end of the incident whether the fire was real, a false alarm, or the operator going home early. It closes on every path out.

The panel fails in four ways. An operator who resets the board the moment any lamp lights, without reading which lamp it was, has built a machine for hiding fires -- and it will hide the lamp that means "the panel's own wiring is broken" just as cheerfully. A log entry reading "alarm at 22:19" with no zone is a record that something happened and nothing more. A pull station wired up as a doorbell teaches everyone to ignore the bell. And a stop valve that jams shut during the incident, swallowing the alarm on its way past, leaves the panel showing all-clear over a burning paint store. Ruby's rescue, raise and ensure reproduce all four exactly.


Syntax or Core Structure

raise is the handle. rescue is the operator at the panel, and it names the zone it is willing to take. else runs when nothing was raised, ensure runs on every path out, and retry sends control back to the top of the begin block. A custom error class is a new lamp on the board: subclass StandardError, and the operator can name it specifically.

# alarm.rb -- one pull station, one panel, one operator.

class AlarmError < StandardError; end
class ZoneFault < AlarmError; end
class PanelDown < AlarmError; end

def read_zone(code)
  raise PanelDown, "panel not answering" if code == 0
  raise ZoneFault, "zone #{code} open circuit" if code > 8
  "zone #{code} clear"
end

def check(code)
  begin
    result = read_zone(code)
  rescue ZoneFault => e
    "fault: #{e.message}"
  rescue AlarmError => e
    "alarm: #{e.class}"
  else
    "ok: #{result}"
  ensure
    puts "  logged code #{code}"
  end
end

puts check(3)
puts check(9)
puts check(0)

attempts = 0

begin
  attempts += 1
  raise PanelDown, "panel not answering" if attempts < 3
  puts "panel answered on attempt #{attempts}"
rescue PanelDown
  retry if attempts < 3
  puts "gave up after #{attempts}"
end

def sound(code)
  read_zone(code)
rescue ZoneFault => e
  puts "  escalating #{e.class}"
  raise
end

begin
  sound(12)
rescue AlarmError => e
  puts "borough fire service: #{e.class}: #{e.message}"
end

begin
  Integer("not a number")
rescue ArgumentError => e
  puts "conversion refused: #{e.class}"
end

puts ZoneFault.ancestors.take_while { |m| m != Exception }.inspect
puts "subclass of StandardError: #{ZoneFault.new("x").is_a?(StandardError)}"

Output:

  logged code 3
ok: zone 3 clear
  logged code 9
fault: zone 9 open circuit
  logged code 0
alarm: PanelDown
panel answered on attempt 3
  escalating ZoneFault
borough fire service: ZoneFault: zone 12 open circuit
conversion refused: ArgumentError
[ZoneFault, AlarmError, StandardError]
subclass of StandardError: true

The interleaving in the first six lines is the whole point of ensure. logged code 3 appears before ok: zone 3 clear because the ensure clause runs while check is still on the stack; the outer puts only gets its string once check has finished. The value of the whole begin expression comes from whichever clause completed -- the else on a clean run, the matching rescue otherwise -- and ensure contributes nothing to it.

Clause order decides everything. ZoneFault is a subclass of AlarmError, so if the two rescue lines were swapped the first one would match every alarm and the ZoneFault branch would be dead code Ruby never warns about. Write the narrowest zone first. The retry block shows the other half of that discipline: retry restarts the begin body unconditionally, so the guard if attempts < 3 is the only thing between you and a loop that never ends.

sound demonstrates two things at once. A method body is an implicit begin, so rescue can sit at method level with no extra nesting. And a bare raise inside a rescue re-raises the exception currently being handled, preserving its class, its message and its backtrace -- which is how you log locally and still let the alarm reach the borough. The last two lines print the hierarchy itself: ZoneFault sits under AlarmError under StandardError, and that ancestry is exactly what a rescue clause matches against.


Technical Depth: What Gets Caught, And What Runs Anyway

A rescue clause is a class test, not a keyword that means "trouble". Which classes it matches, and which slip past it, is decided by one inheritance tree that Ruby ships with -- and the most useful fact about that tree is that the class most people think of as the root is not the one rescue defaults to.

The Exception Tree, And Where The Default Line Sits

ClassWhere it sitsWhat raises itRescue it deliberately
Exceptionroot of the entire treenothing raises it directlyno; this catches Ctrl-C and out-of-memory too
StandardErrorroot of ordinary faultsmost library and application errorsyes; this is the line a bare rescue draws
RuntimeErrorunder StandardErrorraising a bare string, as in raise with a message onlyrarely; it means the author skipped naming the fault
ArgumentErrorunder StandardErrorwrong number or shape of argumentsonly where you can supply a better argument
TypeErrorunder StandardErroran object of the wrong kindrarely; usually a bug further upstream
KeyErrorunder IndexError, under StandardErrorHash fetch on a missing keyyes; it is the intended signal
NoMethodErrorunder NameError, under StandardErrorcalling something that does not existalmost never; it is your typo
NotImplementedErrorunder ScriptError, outside StandardErroran abstract method left unwrittenno, and a bare rescue will not catch it
SignalExceptionunder Exception, outside StandardErrorthe operating system, on Ctrl-Cno

The two rows outside StandardError are the interesting ones. rescue with no class written after it does not mean "everything"; it means rescue StandardError. Ruby drew that line on purpose so that a program-wide safety net cannot accidentally trap the interpreter shutting down or the user pressing Ctrl-C. The cost of the same design is on the row above it: your own NoMethodError sits comfortably inside StandardError, so a bare rescue catches your typos and files them next to genuine data faults.

A Bare rescue Catches Your Bugs Too

def swallow
  yield
rescue => e
  "caught #{e.class}"
end

puts swallow { raise ArgumentError, "bad" }
puts swallow { 1 / 0 }
puts swallow { nil.no_such_method }

begin
  puts swallow { raise NotImplementedError, "not written" }
rescue NotImplementedError => e
  puts "escaped the bare rescue: #{e.class}"
end

Output:

caught ArgumentError
caught ZeroDivisionError
caught NoMethodError
escaped the bare rescue: NotImplementedError

The third line is the one to stare at. Nothing in swallow is wrong with the data; the block called a method that does not exist, and the handler reported it in exactly the same shape as the deliberate ArgumentError above it. In a real batch loop that line becomes "row 4174 rejected" and the typo ships. The fourth line shows the boundary working as designed: NotImplementedError descends from ScriptError, not StandardError, so it walks straight through the bare rescue and out to the caller.

ensure Runs On Every Exit, Including The Ones You Forgot

class ZoneFault < StandardError; end
class PanelDown < StandardError; end

def valve(mode)
  log = []
  begin
    log << "open"
    return "returned early" if mode == :early
    raise ZoneFault, "burst" if mode == :burst
    "normal"
  rescue ZoneFault
    "rescued"
  ensure
    log << "closed"
    puts "  #{mode}: #{log.join(' -> ')}"
  end
end

puts valve(:normal)
puts valve(:early)
puts valve(:burst)

def careful
  raise ZoneFault, "burst"
ensure
  puts "  cleanup ran"
end

begin
  careful
rescue ZoneFault => e
  puts "propagated: #{e.class}"
end

def double_fault
  raise ZoneFault, "first"
ensure
  raise PanelDown, "second"
end

begin
  double_fault
rescue StandardError => e
  puts "survivor: #{e.class}: #{e.message}"
end

Output:

  normal: open -> closed
normal
  early: open -> closed
returned early
  burst: open -> closed
rescued
  cleanup ran
propagated: ZoneFault
survivor: PanelDown: second

Three exits, one cleanup path. :normal falls off the end of the block, :early returns from the middle of it, :burst raises and is rescued -- and open -> closed is printed in all three cases before the caller sees a value. ensure also runs when nothing rescues, which is what careful shows: cleanup happens, then the exception carries on outward untouched. ensure never absorbs an exception and never contributes to the return value.

double_fault is the jammed stop valve. When the ensure clause raises, the exception it raises replaces the one in flight. ZoneFault: first is gone -- not chained, not logged, not recoverable -- and the caller is handed PanelDown: second instead, with a backtrace pointing at the cleanup code rather than at the burst. This is the single most effective way to lose a production incident's root cause, and it happens whenever cleanup code can itself fail: closing a socket that is already dead, flushing a file on a full disk. Cleanup that might raise belongs inside its own begin block.

Put Data On The Exception, Not In The Message

class ZoneAlarm < StandardError
  attr_reader :zone, :detector

  def initialize(zone, detector)
    @zone = zone
    @detector = detector
    super("zone #{zone} #{detector}")
  end

  def evacuate?
    detector == "smoke"
  end
end

[[3, "smoke"], [7, "heat"]].each do |zone, detector|
  begin
    raise ZoneAlarm.new(zone, detector)
  rescue ZoneAlarm => e
    puts "#{e.message} zone=#{e.zone} evacuate=#{e.evacuate?}"
  end
end

Output:

zone 3 smoke zone=3 evacuate=true
zone 7 heat zone=7 evacuate=false

The exception is an object, so it can carry the fields the handler needs to branch on. super("zone #{zone} #{detector}") sets the human-readable message that e.message returns, while zone and detector stay available as data. The alternative -- one RuntimeError whose message the handler parses with a regex -- makes the message format a load-bearing interface, so improving the wording breaks the handler. Note also the two raise forms: raise ZoneAlarm.new(zone, detector) builds the object yourself, whereas the shorthand raise ZoneAlarm, arg passes arg straight to new and works for any initialize that takes a single argument.


Real World Example: One Night On The Gatehouse Panel

Nine events came in between 22:10 and 22:57. Some are real alarms on zones the panel knows about, one is a zone that was decommissioned and never taken off the loop, one is a detector type nobody recognises, and one zone has a known open circuit that the fitter has not got to yet. The morning report has to charge the tenant for genuine call-outs, list every refusal with its reason, and prove that no event was quietly dropped on the way through.

# panel_log.rb -- one night on the gatehouse panel.

class PanelError < StandardError; end

class ZoneFault < PanelError
  attr_reader :zone

  def initialize(zone)
    @zone = zone
    super("zone #{zone} open circuit")
  end
end

class UnknownZone < PanelError
  attr_reader :zone

  def initialize(zone)
    @zone = zone
    super("zone #{zone} not on this panel")
  end
end

ZONES = { 1 => "loading bay", 3 => "paint store", 5 => "press shop", 7 => "boiler room" }
FAULTY = [5]
PENCE = { "smoke" => 45, "heat" => 30 }

EVENTS = <<~ROWS
  2210 3 smoke
  2214 7 heat
  2219 5 smoke
  2223 9 heat
  2231 1 smoke
  2238 3 flame
  2244 5 heat
  2250 0 smoke
  2257 7 smoke
ROWS

def clock(minute)
  format("%02d:%02d", minute / 60, minute % 60)
end

def handle(minute, zone, detector)
  raise UnknownZone, zone unless ZONES.key?(zone)
  raise ZoneFault, zone if FAULTY.include?(zone)
  raise ArgumentError, "unknown detector #{detector}" unless PENCE.key?(detector)

  { minute: minute, zone: zone, detector: detector, pence: PENCE[detector] }
end

rows = EVENTS.lines.map(&:split)
puts "events: #{rows.size}"

accepted = []
refused = Hash.new(0)
detail = []
seen = 0

rows.each do |hhmm, zone, detector|
  minute = hhmm[0, 2].to_i * 60 + hhmm[2, 2].to_i
  begin
    accepted << handle(minute, zone.to_i, detector)
  rescue PanelError, ArgumentError => e
    refused[e.class.name] += 1
    detail << format("  %s  %-13s %s", clock(minute), e.class.name, e.message)
  ensure
    seen += 1
  end
end

accepted.each do |a|
  puts format("  %s  zone %d %-11s %-5s %3dp",
              clock(a[:minute]), a[:zone], ZONES[a[:zone]], a[:detector], a[:pence])
end

detail.each { |line| puts line }

refused.keys.sort.each { |name| puts format("  %-13s x%d", name, refused[name]) }

by_zone = accepted.group_by { |a| a[:zone] }
by_zone.keys.sort.each do |z|
  batch = by_zone[z]
  puts format("  zone %d %-11s n=%d  %3dp", z, ZONES[z], batch.size, batch.sum { |a| a[:pence] })
end

total = accepted.sum { |a| a[:pence] }
puts "accepted #{accepted.size}, refused #{refused.values.sum}, rows seen by ensure #{seen}"
puts format("charge %dp (%d.%02d)", total, total / 100, total % 100)
puts "reconciled: #{accepted.size + refused.values.sum == seen}"

Output:

events: 9
  22:10  zone 3 paint store smoke  45p
  22:14  zone 7 boiler room heat   30p
  22:31  zone 1 loading bay smoke  45p
  22:57  zone 7 boiler room smoke  45p
  22:19  ZoneFault     zone 5 open circuit
  22:23  UnknownZone   zone 9 not on this panel
  22:38  ArgumentError unknown detector flame
  22:44  ZoneFault     zone 5 open circuit
  22:50  UnknownZone   zone 0 not on this panel
  ArgumentError x1
  UnknownZone   x2
  ZoneFault     x2
  zone 1 loading bay n=1   45p
  zone 3 paint store n=1   45p
  zone 7 boiler room n=2   75p
accepted 4, refused 5, rows seen by ensure 9
charge 165p (1.65)
reconciled: true

Every number in that report closes. Four accepted plus five refused is nine, which is what the ensure counter independently observed, so reconciled: true is not a formatting claim but an arithmetic one. The per-zone lines add to 45 + 45 + 75 = 165 pence, the same total the charge line prints from a separate sum, and zone 7 is the only zone that fired twice. Zone 5 raised twice for the same standing fault and contributed nothing, which is exactly right: the tenant is not billed for the panel's own broken wiring.

handle is the pull station and it does three checks in a deliberate order. The zone must exist before it can be faulty, and it must be a real zone before the detector type matters, so each raise narrows the ground the next line stands on. Because the two custom classes take the zone as their initialize argument, the shorthand raise UnknownZone, zone builds the object with the zone attached -- the message is derived from the data rather than the data being buried in the message. The single rescue PanelError, ArgumentError => e clause is the panel: one operator, willing to take either kind of lamp, filing both the same way.

The ensure block does nothing but increment seen, and that is its entire value. It runs on the accepted path and on both refused paths, so it is the only counter in the program that cannot be fooled by a branch someone forgets to update later. Note also what the output does not contain: nothing here lets an exception reach the top level. If one did, Ruby would write the class, message and backtrace to stderr and exit non-zero, and none of those lines would appear in a stdout capture like the one above -- which is why a batch job that "printed nothing wrong" can still have failed.

The design flaw is the ArgumentError in that rescue clause. It is there to catch one deliberate raise -- the unknown detector -- but ArgumentError is a general-purpose class raised by Integer, by format with the wrong arity, and by dozens of library methods. Add a fifth field to the event rows tomorrow, pass one argument too few to handle, and that bug is caught here, tallied as ArgumentError x1, given a plausible refusal line, and silently deducted from the night's charge. A purpose-built UnknownDetector < PanelError would have made the clause say what it means. Three narrower faults sit alongside it: refused is keyed on e.class.name, a bare String, so two error classes with the same short name in different namespaces would merge into one tally row; detail stores formatted strings, throwing away the zone attribute the moment the exception is caught, so grouping refusals by zone would mean parsing the report's own output; and reconciled is printed rather than asserted, so a truncated run still produces a report that looks finished.


Common Mistakes

  1. Using a bare rescue as a general safety net. It catches every StandardError, and that includes NoMethodError and NameError -- your own typos. A loop wrapped in a bare rescue will report a misspelt method as a rejected record and keep going, so the bug survives testing and reaches production disguised as bad data.
  1. Writing rescue Exception. This is the one class you almost never want. It sits above StandardError and so it also traps SignalException from Ctrl-C, SystemExit from exit, and NoMemoryError. A worker loop with rescue Exception cannot be stopped from the terminal and cannot be killed politely by a supervisor.
  1. Listing a superclass before its subclass. Ruby tries rescue clauses top to bottom and takes the first that matches, so a rescue StandardError above a rescue KeyError makes the second clause unreachable. Ruby issues no warning for this, and the dead branch reads as though it works.
  1. Rescuing into silence. An empty rescue body, or the inline modifier form that assigns a fallback and moves on, converts a failure into a plausible-looking value. Nothing records that the fallback was used, so a report full of defaults is indistinguishable from a report full of data.
  1. Using exceptions for ordinary, expected outcomes. A missing optional key, an empty result set and a user who typed nothing are not emergencies. Raising and rescuing for them costs a backtrace capture on every occurrence and, worse, trains readers to treat raised exceptions as routine so they stop looking at the ones that matter.
  1. An unbounded retry. retry re-runs the begin body with no memory of how many times it has already done so. Without a counter and a ceiling, a permanent fault -- a wrong password, a deleted file -- becomes an infinite loop that hammers the failing resource rather than reporting it.
  1. Letting ensure raise or return. An exception raised inside ensure replaces the one already in flight, and an explicit return in ensure discards it entirely. Either way the original fault vanishes with no trace, and the backtrace you are left with points at the cleanup code.
  1. Logging only e.message. The message is prose and may be identical for unrelated causes; the class is the machine-readable part. Log e.class alongside the message, and for anything unexpected log the backtrace too -- e.backtrace gives you the frames, and losing them turns a five-minute diagnosis into an afternoon.
  1. Raising a bare string. raise "something went wrong" produces a RuntimeError, which is the same class as every other bare raise in the codebase. Nothing downstream can rescue your failure without also rescuing everybody else's, so the first named error class you add is the first one anyone can handle selectively.

Best Practices

  • Rescue the narrowest class that actually describes the failure you can do something about. If you cannot name the class, you probably cannot handle the failure either, and letting it propagate is the correct action.
  • Give each application or library one root error class under StandardError and hang everything else off it. Callers then get a single clause that means "a fault from this component" without also swallowing the runtime's own errors.
  • Put the facts on the exception as attr_reader fields and derive the message from them with super. Handlers branch on data; message text is for humans and should be free to change.
  • Treat ensure as cleanup only. Never return from it, and wrap any cleanup step that can itself fail in its own begin so a failing close cannot erase the exception that caused it.
  • Bound every retry with an explicit attempt counter and a ceiling, and make the final failure path say how many attempts were made. Retrying is only useful for faults that are genuinely transient.
  • Let unexpected exceptions escape. A crash with a backtrace at the moment of the fault is far cheaper to diagnose than a report that is quietly short by four rows.
  • Re-raise with a bare raise when you only wanted to log or annotate. It preserves the class, message and backtrace; re-raising a new object throws the original away unless you attach it deliberately.
  • Prefer a predicate or a defaulting lookup over a rescue for absences you expect. Hash#fetch with a default, a key? check or a guard clause states the expectation in the code instead of hiding it in a handler.

Practice Exercises

  1. Close the wide net. Add class UnknownDetector < PanelError to panel_log.rb, raise it in place of the ArgumentError, and narrow the rescue clause to PanelError alone. Then prove the flaw was real: change handle so one call passes too few arguments, and show that the original version filed the resulting ArgumentError as a refused event while the new version lets it crash.
  1. Keep the structure. Store the caught exception objects in refused instead of formatting them into strings at rescue time, then produce a second summary that groups refusals by e.zone and prints the zone name for known zones. Confirm the refusal count still reconciles with the ensure counter.
  1. A bounded retry. Write a read_panel method that raises ZoneFault on its first two calls and succeeds on the third, wrap it in a begin/rescue/retry with a ceiling of three attempts, and print the attempt number it succeeded on. Then set it to fail permanently and show that the ceiling is reached and reported rather than looped forever.
  1. The jammed valve. Write a method that raises one error and whose ensure clause raises a different one, and show which exception the caller receives. Then fix it so cleanup still runs, its own failure is logged, and the original exception is the one that reaches the caller.