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}"
   ensure                    # always executes
      msg = "You entered '#{aNum}'. " + msg
   end
   return msg
end

Try running the previous program and enter a number such as 10, which won’t cause an error, so msg will be assigned in the else clause; then try entering 0, which will cause an error, so msg will be assigned in the rescue clause. Whether or not there is an error, the ensure section will execute to create a msg string that begins with “You entered ” followed by any other messages. For example:

You entered '5'. Result = 20
You entered '0'. Error: divided by 0
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.26.217