【发布时间】:2011-07-02 15:59:58
【问题描述】:
我正在寻找这样的东西:
raise Exception rescue nil
但我发现的最短方法是:
begin
raise Exception
rescue Exception
end
【问题讨论】:
我正在寻找这样的东西:
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
【讨论】:
Exception 替换为 StandardError,因为 it's not a good practice to rescue Exception。
rescue Exception; end 短
只需将左侧括在括号中:
(raise RuntimeError, "foo") rescue 'yahoo'
请注意,只有当异常是 StandardError 或其子类时才会发生救援。请参阅http://ruby.runpaint.org/exceptions 了解更多信息。
【讨论】: