Checking Whether No Error Was Raised

suggest change

You can use an else clause for code that will be run if no error is raised.

def divide(x, y)
  begin
    z = x/y
  rescue ZeroDivisionError
    puts "Don't divide by zero!"
  rescue TypeError
    puts "Division only works on numbers!"
    return nil
  rescue => e
    puts "Don't do that (%s)" % [e.class]
    return nil
  else
    puts "This code will run if there is no error."
    return z
  end
end

The else clause does not run if there is an error that transfers control to one of the rescue clauses:

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

But if no error is raised, the else clause executes:

> divide(10,2)
This code will run if there is no error.
=> 5

Note that the else clause will not be executed if you return from the begin clause

def divide(x, y)
  begin
    z = x/y
    return z                 # Will keep the else clause from running!
  rescue ZeroDivisionError
    puts "Don't divide by zero!"
  else
    puts "This code will run if there is no error."
    return z
  end
end

> divide(10,2)
=> 5

Feedback about page:

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



Table Of Contents