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:
#!/usr/bin/ruby begin i = 1 i/0 rescue ZeroDivisionError puts "you divided by zero putts" end
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:
#!/usr/bin/ruby begin i = 1 File.open("ABSsdt.xyz") i/0 rescue ZeroDivisionError puts "you divided by zero putz" rescue StandardError puts "you had an error of some sort" end
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:
#!/usr/bin/ruby begin if (File.exist? "file_1.rb") puts "file found" else raise "File not found" end end
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!