July 2011
Intermediate to advanced
400 pages
8h 46m
English
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
endWhen you want to append the message from an exception object such as e to a string such as "Error: ", Ruby 1.9 insists ...
Read now
Unlock full access