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.
精彩评论