Where are catch and throw useful in Ruby?

前端 未结 4 609
囚心锁ツ
囚心锁ツ 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条回答
  •  Happy的楠姐
    2021-01-17 19:40

    It's basically a goto, and slightly more akin to a call/cc, except that the control flow is wired up implicitly by name instead of explicitly as a parameter. The difference between throw/catch and raise/rescue is that the former is intended to be used for control flow instead of only exceptional situations, and it doesn't waste time putting together a stack trace.

    Sinatra uses throw/catch for HTTP error codes, where a handler can use throw to cede control to the Sinatra library in a structured way. Other sorts of HTTP frameworks use exceptions, or by returning a different class of response, but this lets Sinatra (for example) try another request handler after catching it.

提交回复
热议问题