| title | Exceptions |
|---|---|
| prev | /language/modules-classes.html |
| next | /language/refinements.html |
Exceptions are raised with the Kernel#raise method. It has three forms:
raise# RuntimeError with default messageraise"Some message"# RuntimeError with custom messageraiseErrorClass,"Some message"# Custom error with custom messageErrorClass must be a subclass of Exception.
See Kernel#raise for more details on raising exceptions.
Exceptions are rescued in a begin/end block:
begin# code that might raiserescue# handle exceptionendIf you are inside a method, you do not need to use begin or end unless you wish to limit the scope of rescued exceptions:
defmy_method# ...rescue# ...endThe same is true for a class, module, and block:
[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 the rescue line:
begin# ...rescue=>exceptionwarnexception.messageraise# re-raise the current exceptionendBy default, StandardError and its subclasses are rescued. You can rescue a specific set of exception classes (and their subclasses) by listing them after rescue:
begin# ...rescueArgumentError,NameError# handle ArgumentError or NameErrorendYou may rescue different types of exceptions in different ways:
begin# ...rescueArgumentError# handle ArgumentErrorrescueNameError# handle NameErrorrescue# handle any StandardErrorendThe exception is matched to the rescue section starting at the top, and matches only once. If an ArgumentError is raised in the begin section, it will not be handled in the StandardError section.
You may retry rescued exceptions:
begin# ...rescue# do something that may change the result of the begin blockretryendExecution 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 for retry, all other uses will raise a SyntaxError. If you wish to retry a block iteration use redo. See Control Expressions for details.
To always run some code whether an exception was raised or not, use ensure:
begin# ...rescue# ...ensure# this always runsendYou may also run some code when an exception is not raised:
begin# ...rescue# ...else# this runs only when no exception was raisedensure# ...end