Exceptions are rescued in a
begin # code that might raise rescue # handle exception end
If you are inside a method, you do not need to use
end unless you wish to limit the scope of rescued exceptions:
def my_method # ... rescue # ... end
The same is true for a
You can assign the exception to a local variable by using
variable_name at the end of the
begin # ... rescue => exception warn exception.message raise # re-raise the current exception end
By default, StandardError and its subclasses are rescued. You can rescue a specific set of exception classes (and their subclasses) by listing them after
begin # ... rescue ArgumentError, NameError # handle ArgumentError or NameError end
You may rescue different types of exceptions in different ways:
begin # ... rescue ArgumentError # handle ArgumentError rescue NameError # handle NameError rescue # handle any StandardError end
You may retry rescued exceptions:
begin # ... rescue # do something that may change the result of the begin block retry end
Execution will resume at the start of the begin block, so be careful not to create an infinite loop.
To always run some code whether an exception was raised or not, use
begin # ... rescue # ... ensure # this always runs end
You may also run some code when an exception is not raised:
begin # ... rescue # ... else # this runs only when no exception was raised ensure # ... end
Ruby Core © 1993–2017 Yukihiro Matsumoto
Licensed under the Ruby License.
Ruby Standard Library © contributors
Licensed under their own licenses.