Ruby - Exception Exception handler


An exception is an error packaged into an object.

The object is an instance of the Exception class or one of its descendants.

You can handle exceptions by trapping the Exception object, optionally using information that it contains to print an appropriate error message.

You can take any actions needed to recover from the error.

The basic syntax of exception handling can be summarized as follows:

   # Some code which may cause an exception
rescue <Exception Class>
   # Code to recover from the exception

When an exception is unhandled, your program may crash, and Ruby is likely to display a relatively unfriendly error message:


x = 1/0
puts( x )


To prevent this from happening, you should handle exceptions yourself.

Here is an example of an exception handler that deals with an attempt to divide by zero:


   x = 1/0# from ww w. ja  v  a  2 s. com
rescue Exception
   x = 0
   puts( $!.class )
   puts( $! )
puts( x )


The code between begin and end is the exception-handling block.

Ruby $! is a global variable to which is assigned the last exception.

Printing $!.class displays the class name, which here is ZeroDivisionError.

Printing the variable $! has the effect of displaying the error message contained by the Exception object.

You can associate a variable name with the exception by placing the "assoc operator" (=>) after the class name of the exception and before the variable name:

rescue Exception => exc

You can now use the variable name (here exc) to refer to the Exception object:

puts( exc.class )
puts( exc )

Related Topic