Rescuing Exceptions… err… I mean StandardError in Ruby

Linux, Ruby

I’ve heard from people how or how not to rescue things that might break in ruby.  And I was confused.
Your basic rescue frame of mind is something like this:

15306 2014 GitHub
Uploaded with plasq‘s Skitch!

This won’t give you a very good description of what you rescued so you can rescue specific errors and exceptions like this:

15307 2014 GitHub
Uploaded with plasq‘s Skitch!

But! I want to catch EVERY POSSIBLE ERROR I MIGHT RUN INTO! So why not just rescue the whole Exception class? Yeah that sounds like a great idea.

15307 2014 GitHub
Uploaded with plasq‘s Skitch!

Ok so that catches anything we might run into BUT NO!!! Its not a great idea. Let’s illustrate:

example.rb
Uploaded with plasq‘s Skitch!

Now let’s say we have a script that is taking FOREVER to do anything like the one above. Let’s send it a kill signal via ctl+c or you could call kill with the process id from the command line. So ready set… kill! Die die die!

Um wait nothing happend…

What did the logger say?

Uh wait what!?!?!

Terminal 2014 bash 2014 142�0
Uploaded with plasq‘s Skitch!

Ah so rescuing Exception rescues Interrupt (ctl+c) and SignalException (kill).  In this case I had to call kill -9 to get the damn thing to die. The kill -9 command is kind of a silver bullet but you can end up with a mess so don’t use it when you don’t have to, like my associate who crashed a whole cluster of servers that ran a large rental video chain’s backend because kill -9 on that weird flavor of linux did a lot more than just kill the one process, it killed everything that didn’t belong to his user (i.e. goodbye oracle db processes)!

What we should do is rescue StandardError unless you really want to rescue things like ScriptErrors (when you’re eval-ing ruby code) or rescue SignalExceptions (like do something before the thing dies).

This should help:

The Ruby Programming Language
Uploaded with plasq‘s Skitch!

One thought on “Rescuing Exceptions… err… I mean StandardError in Ruby

  1. EXCEPT!!! When you’re using Net::Http or Open-URI or such libraries and get your basic “I can’t connect to this website” errors (like timeout, getaddr, and socket errors) that are not part of StandardError so you have to explicitly catch them or get clever with catching Exception but exiting if you get a kill signal.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s