Handling multiple exceptions
suggest changeYou 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 runs for every StandardError, so the rescues below never run
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
# code that may fail
rescue CustomError
# error handling
ensure
# cleanup
end
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents