Christopher J. Meisenzahl CPS, CSTE
Senior Software Testing Consultant
Spherion
christopher.j.meisenzahl@citicorp.com
Re: Newbie: Can some briefly compare raise and throw for me? Thx!
it's best when the text is in the body :-)))
briefly
pigeon% cat b.rb
#!/usr/bin/ruby
def tt
throw :stop
end
catch(:stop) do
tt
end
p "After"
catch(:stop) do
Thread.new { tt }.join
end
p "After"
pigeon%
pigeon% b.rb
"After"
./b.rb:3:in `throw': uncaught throw `stop' in thread 0x81083c8 (ThreadError)
from ./b.rb:12:in `join'
from ./b.rb:12
from ./b.rb:11:in `catch'
from ./b.rb:11
pigeon%
pigeon% cat b.rb
#!/usr/bin/ruby
def tt
raise "stop"
end
tt rescue true
p "After"
Thread.new { tt }.join rescue true
p "After"
pigeon%
pigeon% b.rb
"After"
"After"
pigeon%
Guy Decoux
Can some[one] briefly compare raise and throw for me? Thx!
“raise” raises an error/exception (whatever you want to call it). This
exception - which is an object - is “rescued” later and some error-handling
code performed.
“throw” throws a symbol out into the wilderness, hoping that someone will
"catch" it.
There are distinct similarities in their operation, the most important one
being that they can jump the boundaries of several method invocations (stack
frames) at once. There are probably differences too, but to me, the real
difference is of intent. “raise/rescue/ensure” is for exception handling, and
"throw/catch" is for signalling - generally signalling that something has
finished early and we can quite the whole operation altogether.
The other difference is that I’ve never used throw/catch, and consider it a bit
dodgy. raise/resuce/ensure, OTOH, I use all the time.
See Pickaxe for more information.
Gavin