July 2011
Intermediate to advanced
400 pages
8h 46m
English
If the rescue section executes when an error occurs and ensure executes whether or not an error occurs, how can you specifically execute some code only when an error does not occur?
The way to do this is to add an optional else clause after the rescue section and before the ensure section (if there is one), like this:
begin
# code which may cause an exception
rescue [Exception Type]
else # optional section executes if no exception occurs
ensure # optional exception always executes
endThis is an example:
else.rb
def doCalc( aNum ) begin result = 100 / aNum.to_i rescue Exception => e # executes when there is an error result = 0 msg = "Error: " + e.to_s else # executes when there is no error msg = "Result = #{result}" ...Read now
Unlock full access