Permalink
Browse files

Add explanation + fixture for begin

  • Loading branch information...
1 parent cf0b42b commit 4b83eb88f265a2d8dfc1040dae30d02b68e5bbbb @radar radar committed Sep 20, 2010
Showing with 25 additions and 0 deletions.
  1. +16 −0 explanations/begin.md
  2. +9 −0 fixtures/begin.rb
View
@@ -0,0 +1,16 @@
+## `begin` statement
+
+A `begin` statement is primarily used when a piece of code may raise an exception that we wish to `rescue` from or `ensure` that even if an exception is raised that more code is ran. An example:
+
+ begin
+ boom!
+ rescue Boom => e
+ puts "No more boom."
+ ensure
+ puts "Everything is OK."
+ end
+
+In this example, if the `boom!` method raises a `Boom` exception, this will be caught by the `rescue` statement which assigns the rescued exception to the local variable `e`. Everything after the `rescue` but before the following `end` or `ensure` is the code that will be ran during the `rescue`. To get the stacktrace or message of this exception we can call `stacktrace` and `message` respectively on this object.
+
+The `ensure` statement declares code that should be ran always, regardless of if an exception was rescued.
+
View
@@ -0,0 +1,9 @@
+def explosive
+ begin
+ raise "OH SHIT"
+ rescue
+ puts "Naw it's ok."
+ ensure
+ puts "Seriously. Chill."
+ end
+end

0 comments on commit 4b83eb8

Please sign in to comment.