Exception Handling

Exceptions occur when a program gets off course, and the normal program flow is interrupted. Ruby is prepared to handle such problems with its own built-in exceptions, but you can handle them in your own way with exception handling. Ruby’s exception handling model is similar to the C++ and Java models. Table 10 shows a comparison of the keywords or methods used to perform exception handling in all three languages.

Table 10. C++, Java and Ruby exception handling compared

C++

Java

Ruby

try {}

try {}

begin/end

catch {}

catch {}

rescue keyword (or catch method)

Not applicable

finally

ensure

throw

throw

raise (or throw method)

The rescue and ensure Clauses

Handle errors/exceptions by using the rescue and ensure clauses:

begin
    eval "1 / 0"
rescue ZeroDivisionError
    puts "Oops. You tried to divide by zero again."
    exit 1
ensure
    puts "Tsk. Tsk."
end

The eval method (from Kernel) evaluates a string as a Ruby statement. The result is disastrous, but this time the rescue clause catches the error, gives you a custom report in the form of the Oops string, and exits the program. (exit is another Kernel method; the argument 1 is a catchall for general errors.) You can have more than one ensure clause if your program calls for it.

Instead of giving its default message, that is, ZeroDivisionError: divided by 0, Ruby returns the message in rescue, plus the message in ensure. Even though the program exited at the end of the rescue clause, ensure yields its block, no matter what.

The raise Method

You don’t ...

Get Ruby Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.