A Basic Error Handling Block

suggest change

Let’s make a method to divide two numbers that is 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 Integer

We can rewrite the method by wrapping the risky division operation in a begin...end block and using a rescue clause to print a message and return nil if there is a problem. A bare rescue catches StandardError and its subclasses, not every Exception.

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

# divide(10, 0)   # prints "There was an error"
# divide(10, 'a') # prints "There was an error"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents