From: Josh Cheek Date: 2011-12-06T14:19:14+09:00 Subject: Re: Newbie: Understanding Throw/Catch --f46d04447f1157f1c704b365934a Content-Type: text/plain; charset=ISO-8859-1 On Mon, Dec 5, 2011 at 10:54 PM, Ankush Ganatra wrote: > Hi > > I was just going through various concepts fo Ruby and found one > interesting (but not so useful in real world ) concept of Ruby, i.e. catch > and throw > > I tried on of the example in the book.. > > def dothings( aNum ) > i = 0 > while true > puts( "I'm doing things..." ) > throw( :go_for_tea ) if (i == aNum ) > end > end > catch( :go_for_tea ){ puts "caught here"} > dothings(0) > > The above code gives me output as :: > > caught here.. > i'm doing things... > throw: uncaught throw 'go_for_tea' (Name Error) > > > I have 2 doubts here > > 1. Why is there an error at the end > 2. Why "caught here" is printed before the method is called? > > > > Thanks. > > Regards > > Ankush You got this out of a book? I'd be hesitant to continue learning from it (convention is 2 spaces for indentation, `aNum` should be a_num or better yet `number` or maybe even `integer` depending on intent, the `i=0` does nothing, and if aNum isn't zero, it will get caught in an infinite loop) Anyway, it works this way because the catch block is executed first. If the catch block had thrown the symbol, it would have been caught. But it didn't throw the symbol, so it continued execution. Then, outside of the block, when `dothings(0)` is called, it prints the statement then throws the symbol. But this doesn't happen in a catch block, so it goes uncaught and ultimately raises an error. Run it with these three locations to see the difference: catch :go_for_tea do dothings 0 puts "caught here" dothings 0 end dothings 0 --f46d04447f1157f1c704b365934a--