From: Robert Klemme Date: 2005-10-19T16:57:06+09:00 Subject: Re: Catch/throw vs rescue/raise/retry Edward Faulkner wrote: > On Wed, Oct 19, 2005 at 07:07:05AM +0900, Warren Seltzer wrote: > > There appear to be 2 separate exception mechanisms in Ruby, catch/throw and > > rescue/raise/retry. Is this right? > > Yes, but they're not used for the same thing. > > rescue/raise is used to signal error conditions. This is analogous to > Exceptions in Java or C++. > > Throw/catch is used to unwind the stack to a desired point. It's like > a labeled break. For example: > > catch(:done){ > loop { > do_work > if time_to_stop? throw :done > } > } You probably meant catch(:done){ loop { do_work throw :done if time_to_stop? } } > It's nice because you can break out of arbitrarily nested loops/blocks/etc. Plus you can return something from the throw like this: catch(:done){ loop { do_work throw :done, "result" if time_to_stop? } } Kind regards robert