Ruby Language Catching Exceptions with Begin / Rescue A Basic Error Handling Block

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

Let's make a function to divide two numbers, that's very trusting about its input:

def divide(x, y)
  return x/y
end

This will work fine for a lot of inputs:

> puts divide(10, 2)
5

But not all

> puts divide(10, 0)
ZeroDivisionError: divided by 0

> puts divide(10, 'a')
TypeError: String can't be coerced into Fixnum

We can rewrite the function by wrapping the risky division operation in a begin... end block to check for errors, and use a rescue clause to output a message and return nil if there is a problem.

def divide(x, y)
  begin
    return x/y
  rescue
    puts "There was an error"
    return nil
  end
end

> puts divide(10, 0)
There was an error

> puts divide(10, 'a')
There was an error


Got any Ruby Language Question?