What is the difference between Raising Exceptions vs Throwing Exceptions in Ruby?
Ruby有两种不同的异常机制:抛出/捕获和提升/救援。
为什么我们有两个?
你什么时候应该使用一个而不是另一个?
我认为http://hasno.info/ruby-gotchas-and-caveats可以很好地解释这种差异:
catch/throw are not the same as raise/rescue. catch/throw allows you to quickly exit blocks back to a point where a catch is defined for a specific symbol, raise rescue is the real exception handling stuff involving the Exception object.
raise 、fail 、rescue 和ensure 处理错误,也称为异常throw 和catch 是控制流
Unlike in other
languages, Ruby’s throw and catch are not used for exceptions.
Instead, they provide a way to terminate execution early when no
further work is needed.
(Grimm, 2011)
使用简单的
While the exception mechanism of raise and rescue is great for abandoning execution when things go wrong, it's sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where catch and throw come in handy.
(Thomas and Hunt, 2001)
工具书类
https://coderwall.com/p/lhkkug/don-t-confuse-ruby-s-throw-statement-with-raise提供了一个很好的解释,我怀疑我能改进。总而言之,我在博客上抓取了一些代码示例:
Ruby的
在Ruby中,catch和throw用于什么?对
它们之间的具体行为差异包括:
rescue Foo 将拯救Foo 的实例,包括Foo 的子类。catch(foo) 只捕获同一物体,Foo 。您不仅不能通过catch 类名称来捕获它的实例,而且甚至不能进行相等比较。例如1
2
3catch("foo") do
throw"foo"
end会给你一个
UncaughtThrowError: uncaught throw"foo" (或者2.2之前的Ruby版本中的ArgumentError )可列出多个救援条款…
1
2
3
4
5
6
7
8begin
do_something_error_prone
rescue AParticularKindOfError
# Insert heroism here.
rescue
write_to_error_log
raise
end虽然多个
catch e需要嵌套…1
2
3
4
5catch :foo do
catch :bar do
do_something_that_can_throw_foo_or_bar
end
end裸的
rescue 相当于rescue StandardError 并且是惯用结构。"光秃秃的"catch ,像catch() {throw :foo} 一样,永远抓不到任何东西,不应该使用。