Ruby - rescue else: Execute Code When No Error Occurs

Introduction

You can use else clause to mark code when there is no error.

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:

Demo

def doCalc( aNum )
   begin#  ww  w . j av a2  s  .com
      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}"
   ensure                    # always executes
      msg = "You entered '#{aNum}'. " + msg
   end
   return msg
end

doCalc( 100)
doCalc( "asdf" )

Related Topic