re-engineering
Published in

re-engineering

How to rescue exceptions in Ruby

In JavaScript world, which is the world I came from before joining Shopify, you do try catch blocks like so:

try {
// executes...
} catch (e) {
// e is error object
}

In Ruby, the equivalent is apparently this:

begin
# executes...
rescue => e
# e is the error object
end

Simple.

What I didn’t explicitly pin down for myself is which exceptions is rescue rescuing us from.

In general, we should handle errors as specifically as possible. We don’t want to cast a big net, catching all kinds of error fishes, since we actually want the sharks to lurk beneath the surface and keep the system in order. Okay, bad analogy, but I hope you get the point. Some fishes (errors) are supposed to come up and crash your system so you know that something actually needs fixing.

The above ruby snippet can be rewritten explicitly like this:

begin
# executes...
rescue StandardError => e
# e is the error object
end

Notice StandardError on line 3? Yeah, if we omit that, Ruby unsurprisingly does the right thing for us by catching all Standard Errors, which, by the way, is a list of error types:

source: honeybadger.io

Here’s one learning from today: if we rescue a class of errors (e.g. StandardError), Ruby will also rescue errors that are children classes of that error.

So if I wrote rescue StandardError => e , whenever my program executes code within that begin... rescue... endblock and throws a NameError or ZeroDivisionError , those will be rescued by this block.

This may or may not be behaviour that you intended. But as a start, this really OK.

don’t interrupt the signal interrupt (a type of exception)

We’re fine as long as we don’t do this:

# DON'T DO THISbegin
# executes...
rescue Exception => e
# no no no
end

The reason is this — and I’m basically paraphrasing from this article: this will rescue us from any kinds of exceptions, since all error classes are children of the Exceptionclass. This includes signal interrupts from the operating system, like when we do ctrl + c . We need those things to work.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store