这是最简单的方式来默默地忽略Ruby异常

我正在寻找这样的东西:

raise Exception rescue nil

但我发现的最短路线是这样的:

begin
  raise Exception
rescue Exception
end

def ignore_exception
   begin
     yield  
   rescue Exception
   end
end

现在写你的代码

ignore_exception { puts "Ignoring Exception"; raise Exception; puts "This is Ignored" }

这由ActiveSupport提供:

suppress(Exception) do
   # dangerous code here
end

http://api.rubyonrails.org/classes/Kernel.html#method-i-suppress


只需在左括号中包装:

(raise RuntimeError, "foo") rescue 'yahoo'

请注意,只有当异常是StandardError或其子类时才会发生救援。 有关更多信息,请参阅http://ruby.runpaint.org/exceptions。

链接地址: http://www.djcxy.com/p/25841.html

上一篇: Which is the shortest way to silently ignore a Ruby exception

下一篇: How to rescue an eval in Ruby?