开发者

Which is the shortest way to silently ignore a Ruby exception

开发者 https://www.devze.com 2023-02-12 16:22 出处:网络
I\'m looking for something like this: raise Exception rescue nil But the sho开发者_如何学编程rtest way I\'ve found is this:

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

精彩评论

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