[Bug #20482] [DOC] Clarify about pattern maching guard clause
[ruby.git] / doc / syntax / exceptions.rdoc
blobac5ff78a952fa82bc459351f7358834ae36ffaae
1 = Exception Handling
3 Exceptions are rescued in a +begin+/+end+ block:
5   begin
6     # code that might raise
7   rescue
8     # handle exception
9   end
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:
14   def my_method
15     # ...
16   rescue
17     # ...
18   end
20 The same is true for a +class+, +module+, and +block+:
22   [0, 1, 2].map do |i|
23     10 / i
24   rescue ZeroDivisionError
25     nil
26   end
27   #=> [nil, 10, 5]
29 You can assign the exception to a local variable by using <tt>=>
30 variable_name</tt> at the end of the +rescue+ line:
32   begin
33     # ...
34   rescue => exception
35     warn exception.message
36     raise # re-raise the current exception
37   end
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
41 +rescue+:
43   begin
44     # ...
45   rescue ArgumentError, NameError
46     # handle ArgumentError or NameError
47   end
49 You may rescue different types of exceptions in different ways:
51   begin
52     # ...
53   rescue ArgumentError
54     # handle ArgumentError
55   rescue NameError
56     # handle NameError
57   rescue
58     # handle any StandardError
59   end
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:
67   begin
68     # ...
69   rescue
70     # do something that may change the result of the begin block
71     retry
72   end
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
80 details.
82 To always run some code whether an exception was raised or not, use +ensure+:
84   begin
85     # ...
86   rescue
87     # ...
88   ensure
89     # this always runs BUT does not implicitly return the last evaluated statement.
90   end
92 You may also run some code when an exception is not raised:
94   begin
95     # ...
96   rescue
97     # ...
98   else
99     # this runs only when no exception was raised AND return the last evaluated statement
100   ensure
101     # this always runs.
102     # It is evaluated after the evaluation of either the `rescue` or the `else` block.
103     # It will not return implicitly.
104   end
106 NB : Without explicit +return+ in the +ensure+ block, +begin+/+end+ block will return the last evaluated statement before entering in the `ensure` block.