begin + else
Even after 6+ years, Ruby still continues to surprise and delight me. My latest discovery (thanks to Mauricio’s Happy 2007 challenge) is that begin/end blocks accept (in addition to rescue and ensure) an else clause:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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
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.