Ruby - retry: Attempt to Execute Code Again After an Error

Introduction

You can rerun all the code in a begin..end block using the keyword retry.

The following code prompts the user to re-enter a value if an error such as ZeroDivisionError occurs:

Demo

def doCalc
    begin# from   w  w  w.  j a v  a 2s . com
        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

doCalc()

Result

You could increment a local variable in the begin clause.

Then test the value of that variable in the rescue section, like this:

rescue Exception => e
    if aValue < someValue then
        retry
    end

Here is a complete example.

The following code tests the variable tries to ensure no more than three tries to run the code without error before the exception-handling block exits:

Demo

def doCalc
    tries = 0# w  w w.  j a v  a2  s .c  o m
    begin
        print( "Enter a number: " )
        tries += 1
        aNum = gets().chomp()
        result = 100 / aNum.to_i
    rescue Exception => e
        msg = "Error: " + e.to_s
        puts( msg )
        puts( "tries = #{tries}" )
        result = 0
        if tries < 3 then # set a fixed number of retries
           retry
        end
    else
        msg = "Result = #{result}"
    ensure
        msg = "You entered '#{aNum}'. " + msg
    end
    return msg
end

doCalc()

Result

Related Topic