Custom exceptions in Ruby

Exceptions are classes, just like everything else in Ruby. This post will show you how to create your own custom exceptions without falling into some common traps that snare beginners.

It's easy to create your own exceptions in Ruby. Just follow these steps:

1. Make a New Class

Exceptions are classes, just like everything else in Ruby! To create a new kind of exception, just create a class that inherits from StandardError, or one of its children.

class MyError < StandardError

raise MyError

By convention, new exceptions have class names ending in "Error". It's also good practice to put your custom exceptions inside a module. That means your final error classes will look like this: ActiveRecord::RecordNotFound and Net::HTTP::ConnectionError.

2. Add a message

Every ruby exception object has a message attribute. It's the longer bit of text that's printed out next to the exception name

Example of an exception's message attribute Example of an exception's message attribute

You can specify a message when you raise an exception, like so:

raise MyError, "My message"

And you can add a default message to your custom error class by adding your own constructor.

class MyError < StandardError
  def initialize(msg="My default message")

3. Add a custom data attributes to your exception

You can add custom data to your exception just like you'd do it in any other class. Let's add an attribute reader to our class and update the constructor.

class MyError < StandardError
  attr_reader :thing
  def initialize(msg="My default message", thing="apple")
    @thing = thing

  raise"my message", "my thing")
rescue => e
  puts e.thing # "my thing"

That's it! Creating a custom error or exception in Ruby really isn't that difficult. There is one thing to be aware of. Notice how we always inherited from StandardError in the examples? That's intentional. While there is an Exception class in Ruby, you should NEVER EVER inherit directly from it. For more information about this, check out our article about the differences between Exception and StandardError

Honeybadger has your back when it counts. We're the only error tracker that combines exception monitoring, uptime monitoring, and cron monitoring into a single, simple to use platform.

Our mission: to tame production and make you a better, more productive developer. Learn more

author photo

Starr Horne

Starr Horne is a Rubyist and Chief JavaScripter at 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