Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are catch and throw useful in Ruby?

Tags:

ruby

I really don't see a sane use for these. There is already rescue and raise, so why the need for throw and catch? It seems they are supposed to be used to jump out of deep nesting, but that just smells like a goto to me. Are there any examples of good, clean use for these?

like image 560
ryeguy Avatar asked Jan 07 '10 04:01

ryeguy


1 Answers

Note: It looks like a few things have changed with catch/throw in 1.9. This answer applies to Ruby 1.9.

A big difference is that you can throw anything, not just things that are derived from StandardError, unlike raise. Something silly like this is legal, for example:

throw Customer.new

but it's not terribly meaningful. But you can't do:

irb(main):003:0> raise Customer.new
TypeError: exception class/object expected
    from (irb):3:in `raise'
    from (irb):3
    from /usr/local/bin/irb:12:in `<main>'
like image 137
John Feminella Avatar answered Oct 13 '22 15:10

John Feminella