1= Exception Handling 2 3Exceptions are rescued in a +begin+/+end+ block: 4 5 begin 6 # code that might raise 7 rescue 8 # handle exception 9 end 10 11If you are inside a method you do not need to use +begin+ or +end+ unless you 12wish to limit the scope of rescued exceptions: 13 14 def my_method 15 # ... 16 rescue 17 # ... 18 end 19 20The same is true for a +class+ or +module+. 21 22You can assign the exception to a local variable by using <tt>=> 23variable_name</tt> at the end of the +rescue+ line: 24 25 begin 26 # ... 27 rescue => exception 28 warn exception.message 29 raise # re-raise the current exception 30 end 31 32By default StandardError and its subclasses are rescued. You can rescue a 33specific set of exception classes (and their subclasses) by listing them after 34+rescue+: 35 36 begin 37 # ... 38 rescue ArgumentError, NameError 39 # handle ArgumentError or NameError 40 end 41 42You may rescue different types of exceptions in different ways: 43 44 begin 45 # ... 46 rescue ArgumentError 47 # handle ArgumentError 48 rescue NameError 49 # handle NameError 50 rescue 51 # handle any StandardError 52 end 53 54The exception is matched to the rescue section starting at the top, and matches 55only once. If an ArgumentError is raised in the begin section it will not be 56handled in the StandardError section. 57 58You may retry rescued exceptions: 59 60 begin 61 # ... 62 rescue 63 # do something that may change the result of the begin block 64 retry 65 end 66 67Execution will resume at the start of the begin block, so be careful not to 68create an infinite loop. 69 70Inside a rescue block is the only valid location for +retry+, all other uses 71will raise a SyntaxError. If you wish to retry a block iteration use +redo+. 72See {Control Expressions}[rdoc-ref:syntax/control_expressions.rdoc] for 73details. 74 75To always run some code whether an exception was raised or not, use +ensure+: 76 77 begin 78 # ... 79 rescue 80 # ... 81 ensure 82 # this always runs 83 end 84 85You may also run some code when an exception is not raised: 86 87 begin 88 # ... 89 rescue 90 # ... 91 else 92 # this runs only when no exception was raised 93 ensure 94 # ... 95 end 96 97