Ruby example

How to handle errors in Ruby

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Wrap the code in begin … rescue and name the class you expect: begin; Integer(text); rescue ArgumentError => e; puts e.message; end. Add ensure for cleanup that must always run. When you want a catch-all, write rescue => e, which catches StandardError; never rescue Exception, which also swallows exit and Ctrl-C.

Ruby's version of try, catch and finally is begin, rescue and ensure, with an else for code that runs only when nothing was raised. Ruby also has keywords named catch and throw, but they are not for errors, which trips up readers coming from Java or JavaScript. The sections below cover the begin block and method-level rescue, why a bare rescue catches StandardError and why rescue Exception is a bug, raising your own exception classes with a cause, retry and the rescue modifier, printing backtraces and the current stack, and leaving with throw, exit or abort, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1begin, rescue, else and ensureRecommended

Code that might fail goes between begin and rescue. Each rescue clause names the classes it handles, and => e binds the exception so you can read e.class and e.message. else runs only when nothing was raised, and ensure runs in every case. Inside a method (or a do … end block) you can drop begin: the whole body is the protected part. A begin block is also an expression, so it can give a fallback value.

begin_rescue.rb
# A method body works as a begin block
def parse_age(text)
  age = Integer(text)
rescue ArgumentError => e
  puts "  rescued #{e.class}: #{e.message}"
  nil
else
  puts "  parsed #{age}"
  age
ensure
  puts "  ensure always runs"
end

p parse_age("42")
p parse_age("forty")

# Several rescue clauses: the first match wins
["10", "0", "ten", nil].each do |text|
  puts 100 / Integer(text)
rescue ZeroDivisionError
  puts "#{text}: cannot divide by zero"
rescue ArgumentError, TypeError => e
  puts "#{e.class}: #{e.message}"
end

# begin ... end returns a value
port = begin
  Integer("12abc")
rescue ArgumentError
  8080
end
p port

Output

For "42" the method runs else (parsed 42) and returns 42; for "forty" it runs the rescue clause and returns nil. Both print ensure always runs, but the value of ensure is thrown away: the method returns what else or rescue produced. In the loop, "0" hits the ZeroDivisionError clause, while "ten" and nil share the second one and print their own messages. The loop keeps going after each error because the rescue belongs to the block, not to the whole loop.

2Rescue StandardError, never Exception

Every Ruby error is an Exception, but the ones your code should handle are under StandardError: ArgumentError, NoMethodError, IOError and the rest. A bare rescue or rescue => e catches exactly those. The classes outside StandardError are signals to stop: exit raises SystemExit, Ctrl-C raises Interrupt, and NoMemoryError and ScriptError (which includes LoadError) are not things you can fix from a rescue. rescue Exception catches them all, so a program that wraps its main loop that way cannot be stopped with exit or Ctrl-C.

rescue_exception.rb
# exit raises SystemExit, and rescue Exception catches it
begin
  puts "exiting..."
  exit 2
rescue Exception => e
  puts "swallowed #{e.class} (status #{e.status})"
end
puts "still running"

# Ctrl-C raises Interrupt, which rescue Exception also catches
begin
  raise Interrupt
rescue Exception => e
  puts "swallowed #{e.class}"
end

# Where the classes sit
p SystemExit.ancestors.take(3)
p Interrupt.ancestors.take(4)
p NoMethodError.ancestors.take(4)
stoppers = [SystemExit, Interrupt, NoMemoryError, ScriptError]
p stoppers.map { it.ancestors.include?(StandardError) }

# rescue => e means rescue StandardError => e
begin
  [].fetch(5)
rescue => e
  puts "rescued #{e.class}: #{e.message}"
end

# ...so exit gets through, and ensure still runs
begin
  puts "exiting for real"
  exit
rescue => e
  puts "never printed"
ensure
  puts "ensure runs on exit too"
end
puts "never printed either"

Output

The first block shows the bug: exit 2 should end the program, but rescue Exception turns it into swallowed SystemExit (status 2) and the script prints still running. The ancestor lists show why a bare rescue behaves better: NoMethodError descends from StandardError, while SystemExit and Interrupt go straight to Exception, so all four stoppers print false. In the last block exit passes the rescue => e, ensure still prints, and the script ends with status 0. The one fair use of rescue Exception is logging at the very top of a program, followed by a bare raise to pass it on.

3Raise your own errors, with a cause

raise ArgumentError, "message" raises a class with a message; raise "message" alone raises a RuntimeError. For your own errors, subclass StandardError (not Exception, for the reasons above) and give your library one base class so callers can rescue the whole family. A custom class can carry extra fields; call super(message) so e.message works. When you raise inside a rescue, Ruby stores the original exception in e.cause, and a bare raise re-raises the current exception 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

def check_email(email)
  raise ValidationError.new(:email) unless email.include?("@")
  raise ValidationError.new(:email, "email is too long") if email.size > 20
  email
end

["[email protected]", "nope", "[email protected]"].each do |email|
  puts check_email(email)
rescue ValidationError => e
  puts "#{e.class} on #{e.field}: #{e.message}"
end

# raise Class, message; a bare message is a RuntimeError
begin
  raise ArgumentError, "count must be positive"
rescue => e
  p e
end
begin
  raise "something broke"
rescue => e
  p e
end

# Rescue the base class to catch the whole family
begin
  check_email("nope")
rescue AppError => e
  puts "AppError caught a #{e.class}"
end

# Wrap a low-level error: the original becomes e.cause
class ConfigError < AppError; end

def load_port(text)
  Integer(text)
rescue ArgumentError
  raise ConfigError, "bad port #{text.inspect}"
end

begin
  load_port("80a")
rescue ConfigError => e
  puts e.message
  puts "caused by #{e.cause.class}: #{e.cause.message}"
end

# A bare raise re-raises the current error
begin
  begin
    Integer("x")
  rescue ArgumentError
    puts "logging, then re-raising"
    raise
  end
rescue => e
  puts "outer got #{e.class}"
end

Output

The two bad addresses print email is invalid (the default message) and email is too long, each with the field the error carries. p e shows the class and message together: #<ArgumentError: count must be positive> and #<RuntimeError: something broke>. rescue AppError catches the ValidationError because it is a subclass. load_port turns Ruby's ArgumentError into a ConfigError with a clearer message, and e.cause still holds the original. Python's raise X from e is automatic here; to set the cause yourself, pass cause:, as in raise TypeError, "wrapped", cause: e.

4retry, and the rescue modifier

retry inside a rescue clause jumps back to the start of the begin block (or the method body) and runs it again. It is meant for failures that may pass on a second try, such as a timeout. Always count the attempts: an unconditional retry loops forever on an error that does not go away. In real code, add a short sleep between attempts. The rescue modifier, value rescue fallback, is the one-line form. It catches every StandardError, including the NoMethodError from a typo, so it hides bugs.

retry.rb
class FlakyError < StandardError; end

# A fake service that fails twice, then works
calls = 0
fetch = lambda do
  calls += 1
  raise FlakyError, "timeout on call #{calls}" if calls < 3
  "data from call #{calls}"
end

attempts = 0
begin
  attempts += 1
  puts fetch.call
rescue FlakyError => e
  puts "attempt #{attempts} failed: #{e.message}"
  retry if attempts < 5
  puts "giving up"
end

# The rescue modifier: value rescue fallback
port = Integer("80a") rescue 8080
p port

# It rescues every StandardError, typos included
total = [1, 2, 3].sum_of_all rescue 0
p total

Output

The first two calls fail and the third prints data from call 3; with five failures in a row the script would print giving up instead. attempts lives outside the begin block, so retry does not reset it. The modifier lines print 8080, which is fine, and 0, which is not: sum_of_all does not exist, and the NoMethodError vanished without a trace. Prefer a full rescue ArgumentError, or a method that returns nil on bad input, such as Integer("80a", exception: false).

5Print the backtrace, or the stack without raising

e.backtrace is an array of strings, one per frame, newest first. e.full_message builds the full report Ruby prints for an uncaught error (message, class and every frame), which is what you want in a log; highlight: false keeps terminal color codes out of it. e.backtrace_locations gives the same frames as objects with path, lineno and label. To see the current stack without raising anything, call caller (where the current method was called from) or caller(0) (including the current line).

backtrace.rb
def parse(text)
  Integer(text)
end

def load_config(text)
  parse(text)
end

begin
  load_config("oops")
rescue => e
  puts e.message
  puts "--- e.backtrace (an array of strings)"
  puts e.backtrace
  puts "--- e.full_message (what an uncaught error prints)"
  puts e.full_message(highlight: false)
  loc = e.backtrace_locations[1]
  puts "--- one frame: #{loc.label} at line #{loc.lineno}"
end

# The current stack, without raising anything
def log(message)
  puts "#{message} (from #{caller_locations(1, 1).first})"
end

def save
  log("saving")
  puts caller(0)
end

puts "--- caller"
save

Output

The backtrace reads from the failing call outward: main.rb:2:in 'Kernel#Integer' first, then parse, load_config and main.rb:10:in '<main>'. full_message puts the message on the first frame and prefixes the rest with from, exactly as Ruby does when an error is not rescued. Since Ruby 3.4 frames name the class too ('Object#parse') and use straight quotes, so older answers that show `parse' look different. caller_locations(1, 1) fetches just the caller's frame, which is cheaper than building the whole caller array for a log line.

6Not errors: throw/catch, exit and abort

In Ruby, raise is for errors and throw is for control flow. catch(:tag) runs a block, and throw :tag, value anywhere inside it (even several methods deep) jumps out and makes catch return the value: a clean way to leave nested loops. To end the program, exit takes a status (0 by default) and abort("message") prints the message to stderr and exits with status 1. Both raise SystemExit, so ensure blocks and at_exit hooks still run. exit! skips them.

throw_and_abort.rb
grid = [[1, 2, 3], [4, 99, 6], [7, 8, 9]]

# throw/catch: jump out of nested loops, carrying a value
found = catch(:found) do
  grid.each_with_index do |row, r|
    row.each_with_index do |value, c|
      throw :found, [r, c] if value > 50
    end
  end
  nil
end
p found

# No throw: catch returns the block's value
p catch(:done) { "finished normally" }

# A throw with no matching catch is an error
begin
  throw :nowhere
rescue UncaughtThrowError => e
  puts "#{e.class}: #{e.message}"
end

# at_exit hooks run on exit and abort
at_exit { puts "at_exit hook runs" }

config = {}
if config[:token].nil?
  puts "about to abort"
  abort("error: missing token")
end
puts "never printed"

Output

catch returns [1, 1], the row and column of 99, without checking the rest of the grid. A throw with no matching catch raises UncaughtThrowError, as the third line shows. The run ends with exit code 1: abort writes error: missing token to stderr, the at_exit hook prints its line, and never printed stays unprinted. Use abort for "stop with an error message", exit (or exit 1) for a plain stop, and raise when a caller might want to handle the problem.

7Which should you use?

MethodVerdictBest for
begin / rescue SomeErrorRecommendedAn error you expect and can handle
rescue => eGoodA catch-all: every StandardError
ensureGoodCleanup that must run, even on exit
raise / custom < StandardErrorGoodSignaling your own errors, with a cause
retryWith a limitFailures that may pass on a second try
e.full_message / callerGoodLogging the backtrace or the current stack
catch / throwNot for errorsLeaving nested loops with a value
abort("message")GoodStopping a script with a message, status 1
x rescue yAvoidHides typos and real bugs
rescue ExceptionAvoidSwallows exit and Ctrl-C

Frequently asked questions

What is the Ruby equivalent of try, catch and finally?

try is begin, catch is rescue SomeError => e and finally is ensure; Ruby also has else for code that runs only when nothing was raised. Inside a method or a do … end block you can leave out begin. Ruby's own catch and throw are something else: they jump out of nested code and are not used for errors.

What does a bare rescue catch?

rescue with no class, and rescue => e, catch StandardError and its subclasses: ArgumentError, TypeError, NoMethodError, NameError, ZeroDivisionError, IOError and so on. They do not catch SystemExit (from exit), Interrupt (Ctrl-C), NoMemoryError or ScriptError (which includes LoadError and NotImplementedError), which is the behavior you want.

How do I print the full stack trace of an exception?

Use puts e.full_message(highlight: false) for the same report Ruby prints for an uncaught error, or puts e.backtrace for just the frames, one per line. e.backtrace is nil on an exception you created with new but never raised. For the current stack without an exception, use caller or caller(0).

What is Ruby's version of Python's raise ... from?

Raising inside a rescue clause sets the new exception's cause to the one being handled, so raise ConfigError, "bad port" there is already raise ... from e. To set it yourself, pass the keyword: raise TypeError, "wrapped", cause: e. Read it back with e.cause.

Does ensure run when the method returns early?

Yes. ensure runs on a normal finish, a return, break, next, a raised error and exit, but not on exit!. Its value is ignored, so a method still returns what its body returned. Never write return inside ensure: it replaces the return value and silently discards an error in flight, so def g; raise "boom"; ensure; return 2; end returns 2 with no error.

How do I exit a Ruby script with an error message?

Call abort("error: missing token"): it writes the message to stderr and exits with status 1. warn "message" followed by exit 1 does the same in two steps. Plain exit stops with status 0 (or the status you pass), and exit false is status 1. All of them raise SystemExit, so a rescue Exception around them would keep the program running.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground