Dave Lenhardt wrote:

> Here's another snippet I am wondering on:
> 
> catch (:done) do
>   while line = gets
>     throw :done unless fields = line.split(/\t/)
>     songlist.add(Song.new(*fields))
>   end
> songlist.play
> end
> 
> So, according to the book, it's looking for badly formatted strings.  If 
> there is a badly formatted string, the throw clause is invoked.  Now, 
> the question is, where does the throw clause go.

The throw has to be *inside* a corresponding catch block, and it drops 
you to the end of the catch block.

You can also give a value alongside the throw; if so, this is the value 
"returned" by the catch block itself.

ans = catch(:hello) do
  throw :hello, 2
  puts "Never reached"
  3
end
p ans    # 2

> I see that catch 
> (:done) is right there, but how does the throw clause "find" the catch 
> clause.

It's pretty much the same as an exception. The interpreter winds back 
the stack looking for a matching 'catch' block.

> In other words, I am trying to understand howt his works compared to...
> 
> while line = gets
>   throw :done unless fields = line.split (/\t/)
>   songlist.add(Song.new(*fields))
>    end
> end
> 
> catch :done
>   #handle issues
> end

That won't work, because when the throw executes, there is no enclosing 
matching catch block.
-- 
Posted via http://www.ruby-forum.com/.