summaryrefslogtreecommitdiff
path: root/doc/syntax/exceptions.rdoc
blob: 390eb86256540d8e4f7c5e2f0a4624efff02f4e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
= Exception Handling

Exceptions are rescued in a +begin+/+end+ block:

  begin
    # code that might raise
  rescue
    # handle exception
  end

If you are inside a method you do not need to use +begin+ or +end+ unless you
wish to limit the scope of rescued exceptions:

  def my_method
    # ...
  rescue
    # ...
  end

The same is true for a +class+ or +module+.

You can assign the exception to a local variable by using <tt>=>
variable_name</tt> at the end of the +rescue+ line:

  begin
    # ...
  rescue => exception
    warn exception.message
    raise # re-raise the current exception
  end

By 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
    # ...
  rescue ArgumentError, NameError
    # handle ArgumentError or NameError
  end

You may rescue different types of exceptions in different ways:

  begin
    # ...
  rescue ArgumentError
    # handle ArgumentError
  rescue NameError
    # handle NameError
  rescue
    # handle any StandardError
  end

The 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.

To always run some code whether an exception was raised or not, use +ensure+:

  begin
    # ...
  rescue
    # ...
  ensure
    # this always runs
  end

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

  begin
    # ...
  rescue
    # ...
  else
    # this runs only when no exception was raised
  ensure
    # ...
  end