retry: Attempt to Execute Code Again After an Error

If you think an error condition may be transient or may be corrected (by the user, perhaps?), you can rerun all the code in a begin..end block using the keyword retry, as in this example that prompts the user to re-enter a value if an error such as ZeroDivisionError occurs:

retry.rb

def doCalc
    begin
        print( "Enter a number: " )
        aNum = gets().chomp()
        result = 100 / aNum.to_i
    rescue Exception => e
        result = 0
        puts( "Error: " + e.to_s + "\nPlease try again." )
        retry           # retry on exception
    else
        msg = "Result = #{result}"
    ensure
        msg = "You entered '#{aNum}'. " + msg
    end
    return msg
end

Note

When you want to append the message from an exception object such as e to a string such as "Error: ", Ruby 1.9 insists ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.