---
title: Custom exceptions in Ruby
published: "2015-06-02"
publisher: Honeybadger
author: Starr Horne
category: Ruby articles
tags:
  - Ruby
description: "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."
url: "https://www.honeybadger.io/blog/ruby-custom-exceptions/"
---

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.

```ruby
class MyError < StandardError end 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](https://www.honeybadger.io/images/2015/06/badfilename-1024x95.png)](https://www.honeybadger.io/images/2015/06/badfilename.png) Example of an exception's message attribute

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

```ruby
raise MyError, "My message"
```

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

```ruby
class MyError < StandardError def initialize(msg="My default message") super end end
```

## 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.

```ruby
class MyError < StandardError attr_reader :thing def initialize(msg="My default message", thing="apple") @thing = thing super(msg) end end begin raise MyError.new("my message", "my thing") rescue => e puts e.thing # "my thing" end
```

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](https://www.honeybadger.io/blog/ruby-exception-vs-standarderror-whats-the-difference/)

---

## Try Honeybadger for FREE

Intelligent logging, error tracking, and Just Enough APM™ in one dev-friendly platform. Find and fix problems before users notice.

[Start free trial](https://app.honeybadger.io/users/sign_up)

[See plans and pricing](https://www.honeybadger.io/plans/)
