How to raise any object as a Ruby exception

Ruby's raise syntax gives you a couple of options for specifying the kind of error you want raised. In the code below, I've shown three ways to raiseĀ a RuntimeError.

raise "hello"
raise RuntimeError, "hello"

# ...all of the above result in "RuntimeError: hello"

That's nice, but what happens when I want to raise something other than an exception? What if I wanted to raise a number? Well, Ruby won't let me. I'd get an error message like this:

raise 1
# TypeError: exception class/object expected

Now this message might lead you to believe that raise expects an exception class/object as a parameter. But that's incorrect!

Introducing the exception method

If you do raise foo the raise method doesn't expect foo to be an exception object. It expects that it will get an exception object whenever it calls foo.exception.

The thing to remember is that you can pass ANYTHING to raise, just as long as it has a method called exception that returns an exception.

So, if you wanted to, you could monkeypatch ruby's number classes to allow you to raise a number. Here's what that might look like:

class Fixnum
  def exception"I'm number: #{ self }")

raise 42
# ...results in raise_number.rb:7:in `<main>': I'm number: 42 (RuntimeError)

This is a neat party trick, but could it ever be useful in real life? The main practical application I see for this technique is to separate the logic required to build an exception from the logic that decides to raise the exception. This is certainly a bit of an edge case. But let's see what that might look like.

A possibly practical example

Suppose I want to read a line of data from some kind of IO. It could be network IO, it could be a file. It doesn't really matter. I just want to read the data and see if it's valid.

If the data I read isn't valid, I want to raise an exception. But the exception needs to be tailored to the input. A network connection needs to have different debug info than a local file. I can do that by providing custom exception methods for each kind of input class. Here's some pseudo-ruby showing what that might look like.

# These three classes represent different kinds of IO with different exceptions.
class NetworkConnection
  def exception url, ...)

class LocalFile
  def exception path, ...)

class UnixPipe
  def exception

def read_all(*items)
  items.each do |item|
    if item.readline != "foo"
      # We raise the item, which causes the appropriate exception class to be used. 
      raise item

read_all( ""),"/something"),

Level up your software development career

Join our community of kick-ass developers as we learn engineering, DevOps, cloud architecture, and bootstrapping remote software companies. Tell me more →

We're Honeybadger. We'll never send you spam; we will send you cool shit like exclusive content, memes, and special swag.