Where are catch and throw useful in Ruby?

前端 未结 4 588
囚心锁ツ
囚心锁ツ 2021-01-17 19:20

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 seem

4条回答
  •  无人及你
    2021-01-17 19:35

    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 `
    '

提交回复
热议问题