Checking for Different Errors
suggest changeIf 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) # prints "Don't divide by zero!"
# divide(10, 'a') # prints "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) # prints "Don't do that (NoMethodError)"
In this case, trying to divide nil by 2 is not a ZeroDivisionError or a TypeError, so it is handled by the bare rescue clause, which prints a message showing that it was a NoMethodError.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents