1. Technology
Send to a Friend via Email

Your suggestion is on its way!

An email with a link to:

http://ruby.about.com/od/rubyfeatures/a/exceptions.htm

was emailed to:

Thanks for sharing About.com with others!

You can opt-out at any time. Please refer to our privacy policy for contact information.

Exceptions

Handling Unexpected Conditions

By

Why Use Exceptions?

Computer programs don't always do what they were intended to do. At some time or another a program will fail, either due to a programming mistake or because of an external cause. A file may get accidentally deleted so your program cannot open it or you may try to open the wrong file by mistake. Your network connection may go down and your program may not be able to connect to other computers over the Internet. Whatever the failure, to handle these unexpected conditions, a feature called Exceptions are used.

What are Exceptions?

An exception is a variable that's "raised" or "thrown" when something goes wrong. If an exception is raised, the program stops executing and the Ruby interpreter will look for code that can "catch" or "handle" the exception. For example, if a file is accidentally deleted and your program calls File.open to try to open that file, an exception will be raised.

The Ruby interpreter knows what the problem is : the file you want isn't there. What the Ruby interpreter doesn't know is what to do about the problem. Should the program just exit? Should the program open a different file instead? This is what the code that catches the exception variable--called the "exception handler"--does.

Raising Exceptions

The following example will call a function that raises an exception. When the Ruby interpreter tries to open the file doesntexist.txt, an exception will be raised. The Ruby interpreter will then search upward in the code for an exception handler block starting with the begin keyword. If the Ruby interpreter finds an exception handler block, the block of code starting with the rescue keyword will be executed. If not, the program will exit.

#!/usr/bin/env ruby

begin
  File.open "doesntexist.txt"
rescue
  puts "Could not open file"
end

Catching Excpetions

Each exception variable carries information about the error it encountered. To catch and examine an exception variable, the rescue keyword has a special syntax. The line rescue => e will catch exceptions of any type and store them in the variable called e. The message attribute of the exception variable will often have useful information about the error.

#!/usr/bin/env ruby

begin
  File.open "doesntexist.txt"
rescue => e
  puts "Could not open file"
  puts e.message
end

Throwing Multiple Exception Types

There are often times when more than one type of exception can be thrown. Each exception thrown is an object just like any other object you would assign to a variable. It has a type, it has methods you can call and it has attributes you can access. The exception will often contain information about exactly what went wrong in addition to information about the type of exception. In the following example, an attempt will be made to open doesntexist.txt in write mode. If that succeeds, an attempt will be made to read from the file. Each of these throws a different type of exception, and each one will be handled differently.

#!/usr/bin/env ruby

begin
  f = File.open "doesntexist.txt", "r"
  f.write "test"
rescue Errno::ENOENT => e
  puts "Could not open file"
rescue IOError => e
  puts "Could not write to file"
end

Create Your Own Exceptions

Exceptions are not some internal Ruby voodoo, your code can raise exceptions as well. These exceptions work in the same way, except that you create the exception object yourself. This object can be anything you wish, but it's recommended that you use an object of the Exception type. In this example, the divide function will raise an exception if you try to divide by zero. The exception handling block will catch the exception and print an error message.

#!/usr/bin/env ruby

def divide(x,y)
  if y == 0
    raise Exception.new("divide by zero")
  end

  return x / y
end

begin
  divide( 10, 0 )
rescue Exception => e
  puts e.message
end

There are many Ruby functions that can throw exceptions. The most common examples are the input/output functions, as all of these functions can throw a variety of exceptions. However, there are other, less obvious functions that can throw exceptions, too. To find out if the functions you're using throw exceptions, refer to their documentation.

  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Exceptions

©2014 About.com. All rights reserved.