开发者

Which is the shortest way to silently ignore a Ruby exception

I'm looking for something like this:

raise Exception rescue nil

But the sho开发者_如何学编程rtest way I've found is this:

begin
  raise Exception
rescue Exception
end


This is provided by ActiveSupport:

suppress(Exception) do
   # dangerous code here
end

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


def ignore_exception
   begin
     yield  
   rescue Exception
   end
end

Now write you code as

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


Just wrap the left-hand side in parenthesis:

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

Note that the rescue will only happen if the exception is a StandardError or a subclass thereof. See http://ruby.runpaint.org/exceptions for more info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜