Why not `raise' and `rescue'?
At some point every apprentice is tempted to look for a quick escape from a self-painted corner. The apprentice sees the trap of her own making at the bottom of many nested methods or loops. "I know!" she thinks. "I'll jump out with an exception!"
But therein lies danger: exceptions are meant to be quite literal. One should raise an exception under exceptional circumstances, and only then. The temptation to use exceptions to move about the code is one we all experience; don't worry. But that doesn't make it any less wrong. "Moving about the code" is known in fancy circles as "flow control." Your tools for flow control include if
(and its friends, unless
and else
), Enumerable#each
, for
, method calls, and the like.
The reason not to use exceptions for flow control isn't simply one of semantics, either. Exceptions are designed to provide you, the programmer, with as much information as possible about what went wrong (since they imply a failure). To do this, Ruby's exception system figures out all the methods you called to get where you are -- and this is slow. Control flow code should be fast. Exceptions are slow. One more reason to do things correctly.
...and how do we do things correctly? In the Ruby world, throw
and catch
are an option. Of course, "doing things correctly" is always philosophical and subjective -- but we can pontificate a bit more after a few examples.