| A Basic Error Handling Block Let's make a function to divide two numbers, that's very trusting about its input: This will work fine for a lot of inputs: But not all We can rewrite the function by wrapping the risky division operation in a begin... end block to check for errors, and use a rescue clause to output a message and return nil if there is a problem. |
| Checking for Different Errors 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. If you want to save the error for use in the rescue block: Use a rescue clause with no argument to catch errors of a type not specified in another rescue clause. 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. |
| Retrying In a rescue clause, you can use retry to run the begin clause again, presumably after changing the circumstance that caused the error. If we pass parameters that we know will cause a TypeError, the begin clause is executed (flagged here by printing out "About to divide") and the error is caught as before, and nil is returned: But if we pass parameters that will cause a ZeroDivisionError, the begin clause is executed, the error is caught, the divisor changed from 0 to 1, and then retry causes the begin block to be run again (from the top), now with a different y. The second time around there is no error and the function returns a value. |
| Checking Whether No Error Was Raised You can use an else clause for code that will be run if no error is raised. The else clause does not run if there is an error that transfers control to one of the rescue clauses: But if no error is raised, the else clause executes: Note that the else clause will not be executed if you return from the begin clause |
| Code That Should Always Run Use an ensure clause if there is code you always want to execute. The ensure clause will be executed when there is an error: And when there is no error: The ensure clause is useful when you want to make sure, for instance, that files are closed. Note that, unlike the else clause, the ensure clause is executed before the begin or rescue clause returns a value. If the ensure clause has a return that will override the return value of any other clause! |