How to Handle Exceptions in Ruby
Occasionally, a method will encounter an error, at which point it will fail and tell you about it via the a mechanism called an exception. In Ruby, when exceptions are raised by a method that encounters an error, you'll have rescue your program and handle the error.
Instructions
-
Throw an Exception
-
1
Write some code that will throw an exception, using the raise statement. In Ruby, the raise statement will stop execution of the method, then unwind the program.
-
2
Enclose the call to this method in a matching rescue statement. Otherwise, the program will end and an error message will be displayed on the terminal. The following example shows an averaging function, such as that found in grade book software.
-
-
3
Here, all the test scores are averaged. If the result is more than 100%, there's no choice but to raise an exception because someone has cheated:
def average(num1, num2, num3)
av = (num1 + num2 + num3) / 3.0
if av > 100
raise "Someone cheated, average is #{av}"
else
return av
end
end
Handle the Exception
-
4
Write the rescue statement, calling the average method enclosed in a block with a rescue statement.
-
5
Start the block with "begin." It can have any number of "rescue" statements, and it ends with the "end" keyword. The rescue statement has a type clause as well: a type followed by => and a variable name. Excluding the type will allow the rescue statement to catch all exceptions thrown.
-
6
When executing the rescue statement, the value that was raised is assigned to "e." There can be multiple rescue statements with multiple types to handle different types of errors:
begin
average(98, 92, 130)rescue => e
puts "I caught someone cheating!"
puts "The error message was this: #{e}"
end
Write Else and Ensure Statements
-
7
Create an ensure statement, in addition to the rescue statement. The ensure statement always gets executed when the block is finished. Regardless of how the block exited, whether or not there was an exception raised, or even if it failed to rescue the exception itself, the ensure statement is always executed. The else statement is only executed if there were no exceptions.
-
8
Here you want to make sure the grade book gets closed, so you ensure close_grade book is called:
begin
average(98, 92, 130)rescue => e
puts "I caught someone cheating!"
puts "The error message was this: #{e}">ensure
close_gradebook
end -
9
Write an else statement. If there were no exceptions, the else statement will congratulate the student for not cheating:
else
puts "Good job, and you didn't even cheat!"
-
1
Tips & Warnings
The block is a piece of code that gets executed every time the loop is run.