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