3 Exceptions are rescued in a +begin+/+end+ block:
6 # code that might raise
11 If you are inside a method, you do not need to use +begin+ or +end+ unless you
12 wish to limit the scope of rescued exceptions:
20 The same is true for a +class+, +module+, and +block+:
24 rescue ZeroDivisionError
29 You can assign the exception to a local variable by using <tt>=>
30 variable_name</tt> at the end of the +rescue+ line:
35 warn exception.message
36 raise # re-raise the current exception
39 By default, StandardError and its subclasses are rescued. You can rescue a
40 specific set of exception classes (and their subclasses) by listing them after
45 rescue ArgumentError, NameError
46 # handle ArgumentError or NameError
49 You may rescue different types of exceptions in different ways:
54 # handle ArgumentError
58 # handle any StandardError
61 The exception is matched to the rescue section starting at the top, and matches
62 only once. If an ArgumentError is raised in the begin section, it will not be
63 handled in the StandardError section.
65 You may retry rescued exceptions:
70 # do something that may change the result of the begin block
74 Execution will resume at the start of the begin block, so be careful not to
75 create an infinite loop.
77 Inside a rescue block is the only valid location for +retry+, all other uses
78 will raise a SyntaxError. If you wish to retry a block iteration use +redo+.
79 See {Control Expressions}[rdoc-ref:syntax/control_expressions.rdoc] for
82 To always run some code whether an exception was raised or not, use +ensure+:
89 # this always runs BUT does not implicitly return the last evaluated statement.
92 You may also run some code when an exception is not raised:
99 # this runs only when no exception was raised AND return the last evaluated statement
102 # It is evaluated after the evaluation of either the `rescue` or the `else` block.
103 # It will not return implicitly.
106 NB : Without explicit +return+ in the +ensure+ block, +begin+/+end+ block will return the last evaluated statement before entering in the `ensure` block.