Métodos y Manejo de Excepciones

A def statement that defines a method may include exception-handling code in the form of rescue, else, and ensure clauses, just as a begin statement can.

These exception-handling clauses go after the end of the method body but before the end of the def statement.

In short methods, it can be particularly tidy to associate your rescue clauses with the def statement.

This also means you don’t have to use a begin statement and the extra level of indentation that comes with it.

def method_name(x)
  # The body of the method goes here.
  # Usually, the method body runs to completion without exceptions
  # and returns to its caller normally.
  # Exception-handling code goes here.
  # If an exception is raised within the body of the method, or if
  # one of the methods it calls raises an exception, then control
  # jumps to this block.
  # If no exceptions occur in the body of the method
  # then the code in this clause is executed.
  # The code in this clause is executed no matter what happens in the
  # body of the method. It is run if the method runs to completion, if·
  # it throws an exception, or if it executes a return statement.

Casiano Rodriguez León 2015-01-07