throw and catch are Kernel methods that define a control structure
that can be thought of as a multilevel
throw doesn’t just
break out of the current loop or block but can actually transfer
out any number of levels, causing the block defined with a
catch need not even be in the same method as the
It can be in the calling method, or somewhere even further up the
catch method defines a labeled block of code, and Ruby’s
method causes that block to exit.
catch are much more
general than a labeled
break. For one, it can be used with any kind
of statement and is not restricted to loops.
More profoundly, a
throw can propagate up the call stack to cause a block in an invoking
method to exit.
you probably recognize
catch as the keywords those languages
use for raising and handling exceptions.
Ruby does exceptions
rescue, which we’ll learn about later
in this chapter.
But the parallel to exceptions is intentional.
throw is very much like raising an exception.
And the way
throw propagates out through the lexical scope and then up the
call stack is very much the same as the way an exception propagates out and up.
Despite the similarity to exceptions, it is
best to consider
catch as a general-purpose (if perhaps
infrequently used) control structure rather than an exception
If you want to signal an error or exceptional condition,
raise instead of
The following code demonstrates how
catch can be used to
break out of nested loops:
for matrix in data do # Process a deeply nested data structure. catch :missing_data do # Label this statement so we can break out. for row in matrix do for value in row do throw :missing_data unless value # Break out of two loops at once. # Otherwise, do some actual data processing here. end end end # We end up here after the nested loops finish processing each matrix. # We also get here if :missing_data is thrown. endNote that the
catchmethod takes a symbol argument and a block.
It executes the block and returns when the block exits or when the specified symbol is thrown.
throw also expects a symbol as its
argument and causes the corresponding
catch invocation to return.
catch call matches the symbol passed to
throw, then a
Casiano Rodriguez León 2015-06-18