当涉及到不同错误的连续过滤时,Rescue 语句可以很好地发挥作用:
o = Object.new
begin
o.foo
rescue ArgumentError
puts "Object o does define #foo, but you got the argument number wrong!"
rescue NoMethodError
puts "Object o does not respond to #foo!"
else
puts "That's right!"
end
但是,当涉及到使用不同参数来挽救相同的错误时,这就是我在代码中使用的:
o = Object.new
begin
o.foo
rescue NoMethodError
begin
o.bar
rescue NoMethodError
begin
o.quux
rescue NoMethodError
warn "Object o responds not to basic methods!"
end
end
end
不用说,我不喜欢它。难道没有更聪明的方法来做到这一点吗?