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
The rescue and ensure Clauses
Handle errors/exceptions by using the
begin eval "1 / 0"
rescueZeroDivisionError puts "Oops. You tried to divide by zero again." exit 1
ensureputs "Tsk. Tsk." end
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
ensure yields its block, no matter what.
The raise Method
You don’t ...