Ruby Exception Examples: Begin and RescueHandle exceptions. Use begin, rescue and ensure to enter protected regions.
Exceptions. Bugs crawl about. Programs often cause errors. A file may not exist. A user may input invalid data. We protect against these errors with exceptions.
Keywords. In Ruby we have the begin, rescue and ensure keywords. We use raise to cause trouble. With begin, we enter protected blocks.
An exception is raised when you divide by zero. That is why you should never divide by zero—also it makes no sense. But sometimes these conditions are hard to avoid.
Note: A Ruby program would normally terminate when the ZeroDivisionError is encountered.
However: If you enclose the division statement in a begin block, we have an opportunity to catch or "rescue" the error.
Rescue: In this program we rescue an invalid division expression. We set the result to zero.
Ruby program that uses begin, rescue
# Enter a protected region.
# Try to divide by zero.
i = 1 / 0
# Handle the error.
i = 0
# Display final value.
Many constructs in Ruby allow an optional "else" statement. Begin and rescue also allow "else." Code in the "else" block is executed only if no errors occur within the "begin" block.
Note: Usually a message that states no errors occurred is not needed, but it works well for demonstration.
Tip: In real programs, exceptions usually should not be the "normal" case. Normal operation should have no exceptional events.
Ruby program that uses else
divisor = 2
reciprocal = 1 / divisor
reciprocal = 0
# This is reached when no error is encountered in "begin."
puts "NO ERROR"
Here we use the "raise" statement to raise an exception. We specify a string argument, so the exception we create is of type RuntimeError. And we specify this in the rescue block.
Type: Raise can create an exception of any type. We can specify the type as the first argument to "raise."
Ruby program that uses raise
# This is a bad program.
raise "Bad program error"
rescue RuntimeError => e
# This prints the error message.
Bad program error
In exception handling, we often want to allow an exception to pass through a "rescue" block. This is called "reraising" the exception.
And: With a raise statement, with no argument, the present exception is raised again.
However: We trigger an IndexError. And then, in the "rescue" block, we reraise it. We then rescue it at the method's calling location.
Ruby program that reraises an error
raise IndexError, n if n < 0
# Reraise this error.
# Call the problem method.
# Handle the re-raised error.
puts "IndexError encountered!"
Catch and throw provide an alternative flow, one controlled by labels. We prefix these labels with a colon, as by ":label." In a catch block, we place statements.
Throw: If a throw occurs within the statements in a catch block, the catch block is exited.
Tip: With throw and catch, the labels are matched. In many ways these statements act like "goto" but can pass method boundaries.
Also: For nested loops and method calls, catch and throw can be useful. With them we can reduce the need for flag variables to direct flow.
Ruby program that uses catch, throw
# Throw on a negative number.
if a < 0
# These statements continue until :negative is thrown.
catch :negative do
puts "NOT REACHED"
The retry statement is placed in a rescue block. When retry is reached, the begin statement is entered again. This acts like a "go to" operation.
Note: We usually change variables or an external file before retrying. We attempt to correct the program's state.
Ruby program that uses retry
denominator = 0
# Divide with the denominator integer.
result = 1 / denominator
# Change denominator to 1 and try again.
denominator = 1
Statements in an ensure block are always executed. We add an ensure clause at the end of an exception-handling block. The ensure is run regardless of whether an error is raised.
Tip: An ensure block can be used to perform some cleanup (like deleting a temporary file). It can display a completion message.
Ruby program that uses ensure
y = 10
x = 100 / y
puts "In begin..."
# This is not reached.
puts "In rescue..."
# Do some cleanup.
puts "In ensure..."
There is a cost to raising an exception. And usually it is faster to try to prevent exceptions from occurring. Here I tried to time an exception: the ZeroDivisionError.
Version 1: This code runs a loop 50,000 times. Every 5 iterations, an exception is raised. We handle it with rescue.
Version 2: This code checks the iterator variable "x" against zero each time. It handles zero with a special case.Iterator
Result: It is faster, for a frequent error, to test values with an if-statement. Raising the exception is slower.
Ruby program that times begin, if
n1 = Time.now.usec
# Version 1: use begin, rescue.
5.times do |x|
i = 1 / x
i = 0
n2 = Time.now.usec
# Version 2: use if, else.
5.times do |x|
if x == 0
i = 0
i = 1 / x
n3 = Time.now.usec
# Compute milliseconds total.
puts ((n2 - n1) / 1000)
puts ((n3 - n2) / 1000)
171 ms begin/rescue
15 ms if/else
Exceptions are useful.
Placing statements in begin and rescue blocks is a good way to test them. You can accurately discover what exception they are causing, and where it occurs.
Tip: If a non-essential part of code fails, you may be able to continue the rest of the program without much concern.
Tip 2: Logging an error code in your application is a good way to later correct or debug the application.
Exception handling is critical. It is often the difference between a useless program that cannot be deployed, and one that is effective (or at least limps along). Programs must be robust.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.