Ruby Language Code That Should Always Run


Example

Use an ensure clause if there is code you always want to execute.

def divide(x, y)
  begin
    z = x/y
    return z
  rescue ZeroDivisionError
    puts "Don't divide by zero!"
  rescue TypeError
    puts "Division only works on numbers!"
    return nil
  rescue => e
    puts "Don't do that (%s)" % [e.class]
    return nil
  ensure
    puts "This code ALWAYS runs."
  end
end

The ensure clause will be executed when there is an error:

> divide(10, 0)
Don't divide by zero!   # rescue clause
This code ALWAYS runs.   # ensure clause
=> nil

And when there is no error:

> divide(10, 2)
This code ALWAYS runs.   # ensure clause
=> 5

The ensure clause is useful when you want to make sure, for instance, that files are closed.

Note that, unlike the else clause, the ensure clause is executed before the begin or rescue clause returns a value. If the ensure clause has a return that will override the return value of any other clause!