Ruby 中的 catch 和 throw 在哪里有用? [英] Where are catch and throw useful in Ruby?

查看:25
本文介绍了Ruby 中的 catch 和 throw 在哪里有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不认为这些有合理的用途.已经有了rescueraise,那为什么还需要throwcatch?似乎它们应该被用来跳出深层嵌套,但这对我来说只是闻起来像一个转到.有没有好的、干净的使用这些的例子?

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?

推荐答案

注意: 1.9 中的 catch/throw 似乎发生了一些变化.此答案适用于 Ruby 1.9.

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

一个很大的不同是你可以throw任何东西,而不仅仅是从StandardError派生的东西,不像raise.像这样愚蠢的事情是合法的,例如:

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

这篇关于Ruby 中的 catch 和 throw 在哪里有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆