Ruby Retry and make sure the block is not working

In the code below, try again and make sure the block does not work when there is an error.

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


puts( doCalc )

Please let me know what the problem is.

0
source share
1 answer

Sorry for the previous sentence. I just noticed the actual cause of the error. The following works as you would expect:

def doCalc
  begin
    print( "Enter a number: " )
    aNum = gets().chomp()
    result = 100 / aNum.to_i
  #rescue Exception => e    # - dont catch Exception unless you REALLY need it.
  rescue => e               # - this catches StandardError and is usually enough
    result = 0
    puts( "Error: #{e}\nPlease try again." )   # <-- changed here
    retry   # retry on exception
  else
    msg = "Result = #{result}"
  ensure
    msg = "You entered '#{aNum}'. " + msg
  end
  return msg
end

You actually had three errors occurring one after another.

The first mistake that occurred as you planned was during parsing and dividing. And he was correctly caught rescue Exception => e.

"" "" "". "asd" + e + "asd" , , "". , "" , , - , ensure .

ensure msg , msg nil . , , .

: , add-exception-to-a-string . e. , e.to_s .

+3

All Articles