Handling multiple exceptions

suggest change

You can handle multiple errors in the same rescue declaration:

begin
  # an execution that may fail
rescue FirstError, SecondError => e
  # do something if a FirstError or SecondError occurs
end

You can also add multiple rescue declarations:

begin
  # an execution that may fail
rescue FirstError => e
  # do something if a FirstError occurs
rescue SecondError => e
  # do something if a SecondError occurs
rescue => e
  # do something if a StandardError occurs
end

The order of the rescue blocks is relevant: the first match is the one executed. Therefore, if you put StandardError as the first condition and all your exceptions inherit from StandardError, then the other rescue statements will never be executed.

begin
  # an execution that may fail
rescue => e
  # this will swallow all the errors
rescue FirstError => e
  # do something if a FirstError occurs
rescue SecondError => e
  # do something if a SecondError occurs
end

Some blocks have implicit exception handling like def, class, and module. These blocks allow you to skip the begin statement.

def foo
    ...
rescue CustomError
    ...
ensure
    ...
end

Feedback about page:

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



Table Of Contents