Understanding the Ruby Exception Hierarchy

In this post we look at Ruby's exception class heirarchy, and how you can use it to be as broad or as narrow as you like when rescuing exceptions.

Exceptions are just classes in Ruby. The exception exception hierarchy is made up of all the classes that inherit from Exception.

Here's a the exception hierarchy for Ruby 2.1's standard library.

Exception
  NoMemoryError
  ScriptError
    LoadError
    NotImplementedError
    SyntaxError
  SecurityError
  SignalException
    Interrupt
  StandardError -- default for rescue
    ArgumentError
      UncaughtThrowError
    EncodingError
    FiberError
    IOError
      EOFError
    IndexError
      KeyError
      StopIteration
    LocalJumpError
    NameError
      NoMethodError
    RangeError
      FloatDomainError
    RegexpError
    RuntimeError -- default for raise
    SystemCallError
      Errno::*
    ThreadError
    TypeError
    ZeroDivisionError
  SystemExit
  SystemStackError

Practical uses

The reason that exceptions are arranged into a class tree is so that you can easily rescue similar types of exception.

For example, consider the code:

begin
  do_something
rescue StandardError => e
end

This will rescue not only StandardError, but also any exception that inherits from it. That happens to be pretty much any exception you'll be interested in.

In your own code, you might have all of your custom exceptions inherit from a single base class:

module MyLib

  class Error < StandardError
  end

  class TimeoutError < Error
  end

  class ConnectionError < Error
  end

end

...

begin
  do_something
rescue MyLib::Error => e
  # Rescues any of the exceptions defined above
end


author photo

Starr Horne

Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.


“We’ve looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release.”
Michael Smith
Try Error Monitoring Free for 15 Days