Exception Handling

Exceptions are rescued in abegin/end block:

begin# code that might raiserescue# handle exceptionend

If you are inside a method, you do not need to usebegin orend unless you wish to limit the scope of rescued exceptions:

defmy_method# ...rescue# ...end

The same is true for aclass,module, andblock:

[0,1,2].mapdo|i|10/irescueZeroDivisionErrornilend#=> [nil, 10, 5]

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

begin# ...rescue=>exceptionwarnexception.messageraise# re-raise the current exceptionend

By default,StandardError and its subclasses are rescued. You can rescue a specific set of exception classes (and their subclasses) by listing them afterrescue:

begin# ...rescueArgumentError,NameError# handle ArgumentError or NameErrorend

You may rescue different types of exceptions in different ways:

begin# ...rescueArgumentError# handle ArgumentErrorrescueNameError# handle NameErrorrescue# handle any StandardErrorend

The exception is matched to the rescue section starting at the top, and matches only once. If anArgumentError is raised in the begin section, it will not be handled in theStandardError section.

You may retry rescued exceptions:

begin# ...rescue# do something that may change the result of the begin blockretryend

Execution will resume at the start of the begin block, so be careful not to create an infinite loop.

Inside a rescue block is the only valid location forretry, all other uses will raise aSyntaxError. If you wish to retry a block iteration useredo. SeeControl Expressions for details.

To always run some code whether an exception was raised or not, useensure:

begin# ...rescue# ...ensure# this always runs BUT does not implicitly return the last evaluated statement.end

You may also run some code when an exception is not raised:

begin# ...rescue# ...else# this runs only when no exception was raised AND return the last evaluated statementensure# this always runs.# It is evaluated after the evaluation of either the `rescue` or the `else` block.# It will not return implicitly.end

NB : Without explicitreturn in theensure block,begin/end block will return the last evaluated statement before entering in theensure block.