Thursday, February 12, 2009

begin + else

begin/end blocks accept (in addition to rescue and ensure) an else clause:

begin
# main code here
rescue SomeException
# ...
rescue AnotherException
# ..
else
# stuff you want to happen AFTER the main code,
# but BEFORE the ensure block, but only if there
# were no exceptions raised. Note, too, that
# exceptions raised here won't be rescued by the
# rescue clauses above.
ensure
# stuff that should happen dead last, and
# regardless of whether any exceptions were
# raised or not.
end

If you don’t have an ensure clause, else is pretty much the same as just putting code immediately after the end, but if the order matters (something should happen before ensure, and
only if the main code succeeded, and should not be subject to being rescued if something goes wrong), then else is your man.

http://weblog.jamisbuck.org/2007/2/8/begin-else

No comments: