While the exception mechanism of
for abandoning execution when things go wrong, it's sometimes nice to
be able to jump out of some deeply nested construct during normal
processing. This is where
come in handy.
catch (:done) do
throw :done unless fields = split(/\t/)
defines a block that is labeled with the given name
(which may be a
). The block is executed
normally until a
When Ruby encounters a
, it zips back up the call stack
looking for a
block with a matching symbol.
When it finds
it, Ruby unwinds the stack to that point and terminates the block. If
is called with the optional second parameter, that
value is returned as the value of the
. So, in the previous
example, if the input does not contain correctly formatted lines, the
will skip to the end of the corresponding
only terminating the
loop but also skipping the playing of
the song list.
The following example uses a
to terminate interaction with
the user if ``!'' is typed in response to any prompt.
res = readline.chomp
throw :quitRequested if res == "!"
catch :quitRequested do
name = promptAndGet("Name: ")
age = promptAndGet("Age: ")
sex = promptAndGet("Sex: ")
# process information
As this example illustrates, the
does not have to appear within the
static scope of the