TExcelTAD
Home › Ruby › Ruby Exceptions

Ruby Exceptions

Things go wrong: a file is missing, a user types letters where a number belongs, a network call times out. Ruby signals such problems by raising an exception. If nothing handles it, the program stops with an error message. With begin/rescue you can catch exceptions and react gracefully.

rescue

ruby · try it yourself
begin
  result = 10 / 0
  puts "never printed"
rescue ZeroDivisionError => e
  puts "Oops: #{e.message}"
  puts "Class: #{e.class}"
end
puts "The program keeps running"
Oops: divided by 0
Class: ZeroDivisionError
The program keeps running

As soon as an exception is raised, Ruby skips the rest of the begin block and jumps to a matching rescue. => e stores the exception object so you can read its message.

Handling different errors differently

ruby · try it yourself
def parse_age(input)
  age = Integer(input)
  raise ArgumentError, "age can't be negative" if age.negative?
  "Age: #{age}"
rescue ArgumentError => e
  "Invalid: #{e.message}"
rescue TypeError
  "Invalid: no value given"
end

puts parse_age("42")
puts parse_age("forty")
puts parse_age("-3")
puts parse_age(nil)
Age: 42
Invalid: invalid value for Integer(): "forty"
Invalid: age can't be negative
Invalid: no value given

Inside a method you don't need begin: the whole method body acts as one. Several rescue clauses are checked from top to bottom; you can also list multiple classes in one: rescue TypeError, ArgumentError => e.

else and ensure

ruby · try it yourself
def divide(a, b)
  print "#{a}/#{b}: "
  result = a / b
rescue ZeroDivisionError
  puts "cannot divide by zero"
else
  puts result               # runs only if nothing was raised
ensure
  puts "  (done)"           # always runs
end

divide(9, 3)
divide(1, 0)
9/3: 3
  (done)
1/0: cannot divide by zero
  (done)
Clause Runs when…
rescue a matching exception was raised
else no exception was raised
ensure always — use it to close files, release locks, clean up

Raising exceptions

Use raise to signal a problem yourself:

ruby · try it yourself
def withdraw(balance, amount)
  raise ArgumentError, "amount must be positive" unless amount.positive?
  raise "insufficient funds" if amount > balance   # RuntimeError by default
  balance - amount
end

[[100, 30], [100, -5], [100, 500]].each do |bal, amt|
  puts withdraw(bal, amt)
rescue => e
  puts "#{e.class}: #{e.message}"
end
70
ArgumentError: amount must be positive
RuntimeError: insufficient funds

A bare rescue => e catches StandardError and all its subclasses — which covers nearly every error your code will meet. A do...end block can have its own rescue, as shown above.

The exception hierarchy

text
Exception
├── NoMemoryError, ScriptError, SignalException, SystemExit ...   (don't rescue these)
└── StandardError                                                 (rescue these)
    ├── ArgumentError
    ├── IOError
    ├── IndexError ── KeyError, StopIteration
    ├── NameError ── NoMethodError
    ├── RangeError ── FloatDomainError
    ├── RuntimeError ── FrozenError
    ├── TypeError
    └── ZeroDivisionError

Note: Never write rescue Exception. It would also catch Ctrl+C (Interrupt) and exit (SystemExit), making your program impossible to stop.

Custom exceptions

Create your own error classes by inheriting from StandardError. Giving errors meaningful names makes them easy to rescue precisely:

ruby · try it yourself
class PaymentError < StandardError; end

class CardDeclined < PaymentError
  attr_reader :code

  def initialize(code)
    @code = code
    super("card declined (code #{code})")
  end
end

class InsufficientFunds < PaymentError; end

def charge(card, amount)
  raise CardDeclined.new(51) if card == "expired"
  raise InsufficientFunds, "need #{amount}" if amount > 100
  "charged #{amount}"
end

[["valid", 40], ["expired", 10], ["valid", 250]].each do |card, amount|
  puts charge(card, amount)
rescue CardDeclined => e
  puts "Declined! #{e.message} -> code #{e.code}"
rescue PaymentError => e
  puts "Payment problem: #{e.message}"
end
charged 40
Declined! card declined (code 51) -> code 51
Payment problem: need 250

Rescuing the parent class PaymentError catches every payment-related error at once.

retry

retry restarts the begin block — useful for temporary failures. Always limit the number of attempts:

ruby · try it yourself
attempts = 0
begin
  attempts += 1
  puts "Attempt #{attempts}"
  raise IOError, "network busy" if attempts < 3
  puts "Connected!"
rescue IOError => e
  retry if attempts < 5
  puts "Giving up: #{e.message}"
end
Attempt 1
Attempt 2
Attempt 3
Connected!

Re-raising and wrapping

Sometimes you want to log an error and let it continue upward, or translate a low-level error into your own:

ruby · try it yourself
class ConfigError < StandardError; end

def load_port(settings)
  Integer(settings.fetch(:port))
rescue KeyError, ArgumentError => e
  raise ConfigError, "bad port setting (#{e.message})"
end

begin
  load_port({host: "x"})
rescue ConfigError => e
  puts e.message
  puts "caused by: #{e.cause.class}"
end
bad port setting (key not found: :port)
caused by: KeyError

Ruby remembers the original exception in e.cause.

Test yourself

Which clause always runs, whether or not an exception occurred?

  1. rescue
  2. else
  3. ensure
  4. finally

What does raise "Boom" raise?

  1. StandardError
  2. RuntimeError
  3. Exception
  4. ArgumentError

Which class should custom application errors inherit from?

  1. Exception
  2. StandardError
  3. Object
  4. RuntimeError only