Ruby Language Checking for Different Errors


Example

If you want to do different things based on the kind of error, use multiple rescue clauses, each with a different error type as an argument.

def divide(x, y)
  begin
    return x/y
  rescue ZeroDivisionError
    puts "Don't divide by zero!"
    return nil
  rescue TypeError
    puts "Division only works on numbers!"
    return nil
  end
end

> divide(10, 0)
Don't divide by zero!

> divide(10, 'a')
Division only works on numbers!

If you want to save the error for use in the rescue block:

rescue ZeroDivisionError => e

Use a rescue clause with no argument to catch errors of a type not specified in another rescue clause.

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

> divide(nil, 2)
Don't do that (NoMethodError)

In this case, trying to divide nil by 2 is not a ZeroDivisionError or a TypeError, so it handled by the default rescue clause, which prints out a message to let us know that it was a NoMethodError.