Home / Womply Ruby Style Guide

Ruby Exception Handling Style: Raise, Rescue and Custom Errors

The documentation that used to be at this address is no longer published, and its source was never released under an open license, so it is not reproduced here. This page is an independent guide to the same topic, written for this archive. It is not the project's documentation and is not affiliated with its authors.

Exception handling is where a codebase either tells you clearly what went wrong or hides it. A good style guide section on exceptions is short and opinionated. Here is a set of rules that keeps errors honest.

Rescue specific classes

A bare rescue catches StandardError and everything under it, including typos that raise NoMethodError. Name the errors you actually expect.

# Avoid
begin
  response = client.fetch(order_id)
rescue
  nil
end

# Prefer
begin
  response = client.fetch(order_id)
rescue Timeout::Error, Errno::ECONNREFUSED => e
  logger.warn("Order lookup failed: #{e.message}")
  nil
end

Never rescue Exception. It includes signals and SystemExit, so it can stop a process from shutting down cleanly.

Define your own error hierarchy

Give a library or service one base error, then subclass it. Callers can rescue the whole family or a single case.

module Billing
  class Error < StandardError; end
  class CardDeclined < Error; end
  class InvalidAmount < Error; end
end

raise Billing::InvalidAmount, "Amount must be positive" if amount <= 0

Do not use exceptions for flow control

If a condition is normal, such as a record not being found by a search form, return a value or use a method like find_by that returns nil. Exceptions are for situations the current method cannot handle.

Use method level rescue

Inside a method you can drop the begin keyword, which keeps the happy path flat.

def load_config(path)
  YAML.safe_load(File.read(path))
rescue Errno::ENOENT
  {}
end

ensure and retry

attempts = 0
begin
  attempts += 1
  api.publish(event)
rescue Net::ReadTimeout
  retry if attempts < 3
  raise
end

Keep the original error

When you wrap a low level error in your own, Ruby records the original as cause automatically if you raise inside the rescue block. Keep it that way, and avoid swallowing errors without at least logging them.

More on Womply Ruby Style Guide

Explore the archive