aboutsummaryrefslogtreecommitdiffstats
path: root/doc/syntax/exceptions.rdoc
diff options
context:
space:
mode:
authordrbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2012-12-17 02:26:15 +0000
committerdrbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2012-12-17 02:26:15 +0000
commit29fd59347576ed1ef8fa18534b595b320a939db1 (patch)
tree74b3ad2b3fff9f6212cacfecc1a4e4b6debc31c7 /doc/syntax/exceptions.rdoc
parent810008293fd8ce3a9d3d62dcf2f2229b98c2bd49 (diff)
downloadruby-29fd59347576ed1ef8fa18534b595b320a939db1.tar.gz
* doc/syntax.rdoc: Added syntax guide table of contents
* doc/syntax/exceptions.rdoc: Syntax guide for exceptions * doc/syntax/literals.rdoc: Syntax guide for literals * doc/syntax/methods.rdoc: Syntax guide for methods git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38419 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'doc/syntax/exceptions.rdoc')
-rw-r--r--doc/syntax/exceptions.rdoc79
1 files changed, 79 insertions, 0 deletions
diff --git a/doc/syntax/exceptions.rdoc b/doc/syntax/exceptions.rdoc
new file mode 100644
index 0000000000..390eb86256
--- /dev/null
+++ b/doc/syntax/exceptions.rdoc
@@ -0,0 +1,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
+