else: Execute Code When No Error Occurs

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
end

This 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}" ...

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.