Tutorial by Examples

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') TypeE...
You can save the error if you want to use it in the rescue clause def divide(x, y) begin x/y rescue => e puts "There was a %s (%s)" % [e.class, e.message] puts e.backtrace end end > divide(10, 0) There was a ZeroDivisionError (divided by 0) from ...
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 put...
In a rescue clause, you can use retry to run the begin clause again, presumably after changing the circumstance that caused the error. def divide(x, y) begin puts "About to divide..." return x/y rescue ZeroDivisionError puts "Don't divide by zero!" y = ...
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 ...
Use an ensure clause if there is code you always want to execute. def divide(x, y) begin z = x/y return z rescue ZeroDivisionError puts "Don't divide by zero!" rescue TypeError puts "Division only works on numbers!" return nil rescue => e ...

Page 1 of 1