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 |
|---|---|---|
|
|
|
|
|
|
Not applicable |
|
|
|
|
|
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."
endThe 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access