Exception Handling

Exception Handling

Exceptions are rescued in a begin/end block:

begin
  # code that might raise
rescue
  # handle exception
end

If you are inside a method, you do not need to use begin or end unless you wish to limit the scope of rescued exceptions:

def my_method
  # ...
rescue
  # ...
end

The same is true for a class or module.

You can assign the exception to a local variable by using => variable_name at the end of the rescue line:

begin
  # ...
rescue => exception
  warn exception.message
  raise # re-raise the current exception
end

By default, StandardError and its subclasses