Published in


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:

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


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:

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

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:


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

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.




notes from the field of software engineering

Recommended from Medium

ReactJS, single-page applications(SPA) for the rest of us

JetThoughts receives First Review on Thank you

Optimizing Docker file while Preserving Readability

Starting with Flutter: Channels

CentOS vs Ubuntu

Send Charts In Email Using Google Apps Script

Konsep Agile dalam pengembangan Aplikasi

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
Nick Ang

Nick Ang

Software Engineer @ Shopify. Dad, rock climber, writer, something something. Big on learning everyday.

More from Medium

“Writing code that writes code” or What is Meta Programming in Ruby?

Implement Stack in Ruby to Solve Problem

Ruby Splat Operator

The Basics of Serializer: A Rails guide