Handling Exceptions in Ruby

Dealing with exceptions is a big part of any object oriented programmer’s job. We need to be able to recover from things like connect failures or syntax errors, and do so gracefully. Thankfully, raising and “rescuing” exceptions in Ruby is a fairly easy task. Let’s start with a basic example. We all know that dividing by zero is a very bad thing, so lets tackle that scenario.

For fun let’s test this scenario out in irb. If you didn’t know already, irb is a ruby shell that allows you to execute ruby code on a line-per-line basis and is a great way of checking those one-liners. Lets fire it up and give you a very brief exposure to it.

Note: Ubuntu/Debian users, if you don’t have irb you can install it simply by running:

sudo apt-get install irb

On to the goods… Open up your favorite terminal session and type in the following into an irb session:


Your output should look like this:

codenomad@sparta:~$ irb
irb(main):001:0> i=1
=> 1
irb(main):002:0> i/0
ZeroDivisionError: divided by 0
  from (irb):2:in `/'
  from (irb):2

As you can see you can assign values to a variable, and perform a quick operation on it in irb. You can go ahead and quit irb by typing in “quit”, and we’ll start writing a script to catch this troublemaking scenario.

Handing exceptions in Ruby is referred to as “Rescuing”. In Ruby to rescue exceptions we need to surround our trouble code with a begin/end statement. Below you’ll find that I’ve surrounded our divide by zero scenario by this begin/end structure, and rescued the exception by putting a rescue clause right before the ‘end’. Add the following to a file called rescue.rb:

  i = 1
  rescue ZeroDivisionError
    puts "you divided by zero putts"

Make the file executable and let’s run it:

~$ chmod +x rescue.rb
~$ ./rescue.rb
you divided by zero putts

What if you just wanted to rescue any type of standard error? Well, lets modify our script again to rescue a file open error using StandardError:

  i = 1
  rescue ZeroDivisionError
    puts "you divided by zero putz"
  rescue StandardError
    puts "you had an error of some sort"

Run it, and you should get something like this:

~$ ./rescue.rb
you had an error of some sort

Be sure to check the Ruby documentation when writing your code, and you can see what exceptions can be through by different method calls. (ie look at the Array.fetch() method call. )

Now that you know how to rescue exceptions and where to look for the types of exceptions a method call can make, what about raising exceptions? Well, thats just as easy lets make a new script named raise.rb and add the following:

 if (File.exist? "file_1.rb")
  puts "file found"
  raise "File not found"

If you don’t have file_1.rb in your running directory, this code will raise an exception! It’s as easy as that! For a quick list of exceptions check out Zenspider’s QuickRef site. At this point you have a basic idea of how to handle exceptions, whether you raise them or rescue them, in Ruby. Get out there and get scripting, and be sure to let us know how it goes!

Tags: ,


No Responses to “Handling Exceptions in Ruby”

  1. Mark Wilden October 29, 2008 at 9:33 am #

    In general, exceptions shouldn’t be used for normal processing flows like password validation. Exception handling is more like goto and setjmp/lngjmp than more structured programming constructs. Exceptions are best used for situations where the code that detects the error is not the best code to handle the error (such as in libraries).

    Also, the word is spelled ‘putz.’ :)

    Otherwise, a nice, clear explanation.

  2. rgomez October 29, 2008 at 2:50 pm #

    Thanks for the comment. I agree, I failed to mention the fact that exceptions should be used specifically for error scenarios as a means of dealing with abnormal situations gracefully. I don’t want to promote bad coding habits!! Again, thanks for the comment!

Leave a Reply

two − = 1