Ruby Language Catching Exceptions with Begin / Rescue Code That Should Always Run

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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!



Got any Ruby Language Question?