Thuta Learning
Ruby
AdvancedProgrammingBeginner

Exceptions & Ensure

RubyLesson 2235 min

What you'll walk away with

  • Say when each of the begin/rescue/else/ensure clauses runs
  • Order rescue clauses from specific to general and explain why rescue Exception is dangerous
  • Use every form of raise, including re-raising and cause:
  • Define custom StandardError subclasses that carry extra data
  • Write a bounded retry

Explain it simply

Exceptions in plain language

An exception is Ruby's way of saying "I cannot carry on normally". When something goes wrong, such as dividing by zero or reading a file that does not exist, Ruby creates an exception object and starts unwinding: it leaves the current method, then the method that called it, and so on, looking for code that says it can deal with this kind of problem. begin ... rescue is that code. If nobody handles it, the program stops and prints the message and a backtrace.

ensure is the clean-up crew: its code runs whether the work succeeded, failed or even returned early. Use rescue to decide what to do about a failure, and ensure to put things back, such as closing a file or releasing a lock.

Problem → Why → Solution

The problem: one error ends the whole program

A script reads prices typed by users and doubles them. One day somebody types 12 USD. Integer("12 USD") raises ArgumentError, nothing handles it, and the whole program ends on that line, so the lines after it never run and any half-finished work is simply abandoned.

The tempting fix is to swallow everything with a bare rescue that returns nil, or even rescue Exception. That removes the crash but also removes the information: a typo in your own code now looks like bad user input, and the program carries on with a nil nobody expected. The aim is to handle the failures you expect, in the place that knows what to do, and let everything else stay loud.

price_crash.rb
def load_price(text)
  Integer(text) * 2
end

puts load_price("12")
puts load_price("12 USD")   # ArgumentError ends the whole program here
puts "never printed"

Handle what you expect, let the rest be loud

Exceptions travel up the call stack until something rescues them, so the code that understands the problem can be far from the code that noticed it. Rescuing a specific class lets you recover from the one failure you planned for, while a surprise still reaches the surface with its message and backtrace intact. ensure adds the missing piece, making sure clean-up code runs on every path.

Core concept: raise, rescue, else and ensure

raise creates an exception object, an instance of a class that descends from Exception, and starts unwinding the call stack. Each method it leaves is abandoned on the spot. If a matching rescue clause is found, execution continues there; if the exception reaches the top of the program, Ruby prints the message with a backtrace and exits with an error status. The object carries the details: e.message is the human-readable text, e.class says what kind of problem it is, and e.backtrace lists where it happened.

A begin block has up to four clauses. The body runs first. rescue runs only if the body raised a matching exception. else runs only if the body finished without raising, and an exception raised inside else is not caught by the rescue clauses of the same begin. ensure always runs, whether the body succeeded, failed or hit a return, which makes it the right place for clean-up. A method body can use rescue, else and ensure directly, with no begin, and a do...end block can do the same.

Rescue clauses are tried from top to bottom and the first one that matches wins, so list specific classes before general ones; a broad StandardError placed first makes the clause below it unreachable. rescue => e with no class means StandardError, which covers the errors programs normally cause: ArgumentError, TypeError, ZeroDivisionError, NoMethodError, KeyError, IOError and RuntimeError. Never write rescue Exception. Exception also contains SystemExit, which exit raises, Interrupt, which Ctrl-C raises, and NoMemoryError, so rescuing it can make a program impossible to stop.

raise has several forms. raise "text" raises a RuntimeError. raise ArgumentError raises that class with its name as the message, and raise ArgumentError, "bad value" adds your own message. raise ArgumentError.new("bad value") passes an object you built yourself. A bare raise inside a rescue clause re-raises the exception currently being handled. When you raise a new exception while rescuing another, Ruby records the old one as the new exception's cause automatically, and raise X, cause: other sets it explicitly.

Mental model: a problem travelling upward
  1. raise creates an exception object
  2. Ruby unwinds up the call stack
  3. First matching rescue handles it
  4. ensure runs on every path out

The problem keeps climbing until a rescue claims it, and ensure runs whichever way the code leaves the block.

General pattern

ruby
begin
  risky_work
rescue SpecificError, OtherError => error
  handle(error)               # runs only for these classes
rescue StandardError => error
  log(error.message)          # broader, so it comes last
else
  on_success                  # only when nothing was raised
ensure
  clean_up                    # always runs
end
raise CustomError, "message"

Order the rescue clauses from specific to general; => error stores the exception object in a variable. else runs on success and ensure always runs. The last line shows raise with your own class and message.

Example: rescue, else and ensure in safe_divide

safe_divide below uses a begin with two rescue clauses, an else and an ensure. Watch the order of the printed lines: for the successful call the else line comes before the ensure line, and for the failing calls the ensure line still prints even though the rescue clause returned nil.

The messages "divided by 0" and "String can't be coerced into Integer" in the output are what Ruby 4.0.9 prints. They have been stable across recent Ruby versions, but treat a message as display text and do not compare against it in code.

safe_divide.rb
def safe_divide(a, b)
  begin
    result = a / b
  rescue ZeroDivisionError => e
    puts "error: #{e.message}"
    return nil
  rescue TypeError => e
    puts "type problem: #{e.message}"
    return nil
  else
    puts "ok: #{result}"
  ensure
    puts "finished #{a} / #{b.inspect}"
  end
  result
end

p safe_divide(10, 2)
p safe_divide(1, 0)
p safe_divide(4, "x")

Code breakdown

  1. The risky lineresult = a / b

    This is the only line in the body that can raise. Keeping the body this small makes it obvious what the rescue is protecting.

  2. A specific rescuerescue ZeroDivisionError => e

    It catches ZeroDivisionError only. e.message is "divided by 0", and other errors, such as a NoMethodError, pass straight through this clause and keep climbing.

  3. return inside rescuereturn nil

    A return inside rescue leaves the method, but ensure still runs on the way out. That is why "finished 1 / 0" appears in the output.

  4. The else clauseputs "ok: #{result}"

    else runs only when nothing was raised, so the success report belongs here. result was assigned in the body, so it is visible inside else.

  5. The ensure clauseputs "finished #{a} / #{b.inspect}"

    ensure runs on all three calls. Using b.inspect shows "x" with its quotes, so you can see what type it was, which is handy in log lines.

  6. A TypeError casep safe_divide(4, "x")

    4 / "x" raises TypeError, and the second rescue clause handles it. Each clause can deal with a different failure in its own way.

You should see
ok: 5
finished 10 / 2
5
error: divided by 0
finished 1 / 0
nil
type problem: String can't be coerced into Integer
finished 4 / "x"
nil
The life of a begin block
  1. Run the body
  2. Did it raise an exception?
  3. Find the first matching rescue, top to bottom
  4. With no exception, run else
  5. Always run ensure

The exception matches a rescue

rescue body runs, then ensure

No exception was raised

else runs, then ensure

The order of rescue, else and ensure

The best way to remember the clause order is to watch it with print lines. In the trace below, A succeeds and B raises. A gives body, else, ensure; B stops partway through the body and gives rescue, ensure, with no else. The method is written with a method-level rescue, so no begin is needed. Avoid writing return inside ensure: a return there silently discards the exception that was on its way up.

clause_order.rb
def trace(label, fail: false)
  puts "#{label}: start"
  raise IOError, "disk error" if fail
  puts "#{label}: body finished"
rescue IOError
  puts "#{label}: rescue"
else
  puts "#{label}: else"
ensure
  puts "#{label}: ensure"
end

trace("A")                  # start, body finished, else, ensure
trace("B", fail: true)      # start, rescue, ensure

def early
  return :from_body
ensure
  puts "ensure still runs"
end
p early                     # prints the ensure line, then :from_body

retry, with a limit

retry jumps from a rescue clause back to the start of the begin block and tries again. It suits short-lived failures such as a network timeout. Without a limit, though, something that is truly broken becomes an endless loop, so keep a counter and re-raise once the limit is reached. retry jumps without running ensure, so ensure runs just once, when the block is finally left.

bounded_retry.rb
attempts = 0

begin
  attempts += 1
  puts "attempt #{attempts}"
  raise IOError, "temporary failure" if attempts < 3
  puts "succeeded"
rescue IOError => e
  if attempts < 3
    puts "  #{e.message}, retrying"
    retry
  end
  puts "giving up"
end

Custom errors, re-raise and cause

Give your application's failures their own classes. Keep a base class such as class AppError < StandardError; end and add subclasses such as ValidationError < AppError, so a caller can rescue AppError for everything or a single subclass for one case. Without a message, the message is the class name. To carry extra data, override initialize and call super(message). When you raise a new exception inside a rescue, Ruby records the cause for you, and a bare raise sends the current exception onward unchanged.

custom_errors.rb
class AppError < StandardError; end

class ValidationError < AppError
  attr_reader :field

  def initialize(field, message = "#{field} is invalid")
    @field = field
    super(message)
  end
end

class ConfigError < AppError; end

begin
  raise ValidationError.new(:email)
rescue AppError => e
  puts "#{e.class} field=#{e.field} message=#{e.message}"
end

begin
  raise ValidationError, :age
rescue AppError => e
  puts "#{e.class} field=#{e.field} message=#{e.message}"
end

def load_port(text)
  Integer(text)
rescue ArgumentError
  raise ConfigError, "port must be a number"
end

begin
  load_port("80x")
rescue ConfigError => e
  puts e.message                  # port must be a number
  puts e.cause.class              # ArgumentError
  puts e.cause.message            # invalid value for Integer(): "80x"
end

begin
  begin
    raise "low-level failure"
  rescue => error
    puts "logging: #{error.message}"
    raise                         # same exception continues upward
  end
rescue => again
  puts "outer sees: #{again.message}"
  puts again.equal?(error)        # true
end

Why you never rescue Exception

The top Exception class is wider than most people expect. exit itself raises SystemExit, so rescue Exception swallows even a request to stop the program. The picture below shows the hierarchy and that a bare rescue covers only what sits under StandardError. ScriptError, which contains NotImplementedError, is outside a bare rescue too.

text
A slice of the exception hierarchy
----------------------------------
Exception
 +-- NoMemoryError
 +-- ScriptError ------- NotImplementedError
 +-- SignalException --- Interrupt        (Ctrl-C)
 +-- SystemExit                           (exit)
 +-- StandardError        <- a bare "rescue" catches from here down
      +-- ArgumentError
      +-- IOError
      +-- IndexError ----- KeyError, StopIteration
      +-- NameError ------ NoMethodError
      +-- RuntimeError --- FrozenError
      +-- TypeError
      +-- ZeroDivisionError
exception_hierarchy.rb
begin
  exit 2
rescue SystemExit => e
  puts "exit raised SystemExit with status #{e.status}"
end

p SystemExit.ancestors.first(3)       # [SystemExit, Exception, Object]
p ArgumentError.superclass            # StandardError
kinds = [ZeroDivisionError, KeyError, NotImplementedError, Interrupt]
p kinds.map { |k| k.ancestors.include?(StandardError) }   # [true, true, false, false]

begin
  Integer("x")
rescue StandardError
  puts "first clause wins"
rescue ArgumentError
  puts "unreachable"
end

In real projects

Where this shows up in real projects

Web frameworks use exceptions as the boundary between code that fails and code that responds: a controller rescues a known error such as a missing record and turns it into a 404 page, while an unexpected exception is reported to an error tracker and shown as a generic 500. Libraries define their own error hierarchy, for example one base class per gem with specific subclasses, so a caller can rescue the whole library with one clause or a single failure with another.

Background jobs and API clients combine exceptions with retry: transient problems such as a timeout or a refused connection are retried a few times with a delay, while permanent ones such as a validation failure are reported immediately. Files and network handles are always released in ensure or by block-form methods like File.open. When logging, record the class, the message and the backtrace, keep the cause chain, and never put passwords, tokens or card numbers in an exception message, because messages end up in logs and error dashboards.

Common mistakes

Common mistakes

1. rescue Exception, or a bare rescue that returns nil

rescue Exception swallows exit, Ctrl-C and out-of-memory errors, making the program hard to stop, and a rescue; nil; end silently hides every mistake. Name the class you actually want to handle and let unknown failures stay loud. The modifier form x rescue nil also hides every StandardError.

2. Putting a broad clause before a specific one

If rescue StandardError comes before rescue ArgumentError, the first clause also catches ArgumentError, so the second one never runs, and Ruby reports no error about it. Put the most specific clause at the top and the general one at the bottom.

3. A retry with no limit

Retrying a broken service without a counter turns the program into an endless loop that floods the log. Keep an attempt counter, raise the error once the limit is reached, and where you can, wait briefly between tries.

4. Making callers tell errors apart by their message text

raise "invalid" is just a RuntimeError, so callers must parse the message to know what happened, and a one-word change breaks them. Declaring a dedicated class such as ValidationError and rescuing it by class is far sturdier.

Best practices

Best practices

  • Put only the lines that can fail inside begin, and rescue only a class you know how to handle.
  • Release files, locks and connections in ensure or with block-form methods.
  • Make a base class and specific subclasses for your application's errors, and keep the cause when you wrap an existing error.
  • Never put secrets in an exception message, and in tests check the class rather than the message text.

Mini challenge

Mini challenge: with_retries

Write a with_retries helper that retries a TemporaryError up to a limit but never retries a PermanentError.

  • with_retries(max_attempts) yields the attempt number to the block
  • On TemporaryError print "attempt N: message" and retry until the limit, then raise a PermanentError saying "gave up after N attempts"
  • Print "cleanup after attempt N" from ensure (remember that retry does not run ensure)
  • Do not rescue PermanentError; let it travel up immediately
retries.rb
class TemporaryError < StandardError; end
class PermanentError < StandardError; end

def with_retries(max_attempts)
  # TODO: count attempts and yield the attempt number
  # TODO: retry on TemporaryError until max_attempts, then raise PermanentError
  # TODO: print "cleanup after attempt N" from ensure
end

# TODO: a block that succeeds on the 3rd attempt
# TODO: a block that always fails with TemporaryError, limit 2
# TODO: a block that raises PermanentError at once; it must not be retried

Expected: Expected output: attempt 1: timeout attempt 2: timeout cleanup after attempt 3 result: paid attempt 1: timeout attempt 2: timeout cleanup after attempt 2 failed: gave up after 2 attempts cause: TemporaryError cleanup after attempt 1 failed: card declined

Show hint

Keep attempts = 0 outside the begin and do attempts += 1 inside it, so a retry does not reset the counter. Raising PermanentError inside the rescue attaches the old TemporaryError as its cause automatically.

Show solution
retries.rb
class TemporaryError < StandardError; end
class PermanentError < StandardError; end

def with_retries(max_attempts)
  attempts = 0
  begin
    attempts += 1
    yield attempts
  rescue TemporaryError => e
    puts "attempt #{attempts}: #{e.message}"
    retry if attempts < max_attempts
    raise PermanentError, "gave up after #{attempts} attempts"
  ensure
    puts "cleanup after attempt #{attempts}"
  end
end

result = with_retries(3) do |n|
  raise TemporaryError, "timeout" if n < 3
  "paid"
end
puts "result: #{result}"

begin
  with_retries(2) { raise TemporaryError, "timeout" }
rescue PermanentError => e
  puts "failed: #{e.message}"
  puts "cause: #{e.cause.class}"
end

begin
  with_retries(3) { raise PermanentError, "card declined" }
rescue PermanentError => e
  puts "failed: #{e.message}"
end

Quick quiz 1 / 3

What does begin; Integer("x"); rescue StandardError; puts "A"; rescue ArgumentError; puts "B"; end print?

Quick quiz 2 / 3

Which exception is NOT caught by a rescue => e with no class?

Quick quiz 3 / 3

In def load_port(text); Integer(text); rescue ArgumentError; raise ConfigError, "port must be a number"; end, what does e.cause.class give after rescuing the ConfigError?

What to remember

  • The begin body runs first; rescue runs only for a matching exception, else only when nothing was raised, and ensure always.
  • Order rescue clauses from specific to general and never write rescue Exception; a bare rescue catches StandardError only.
  • raise has the forms raise "text", raise Klass, "msg", raise Klass.new(...), a bare raise and cause:, and a raise inside a rescue records the cause automatically.
  • Declare your own errors as StandardError subclasses, always bound a retry, and remember that ensure does not run on retry, only once when the block is finally left.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.