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!