这是默默忽略Ruby异常的最短路径

fgu*_*len 24 ruby exception-handling

我正在寻找这样的东西:

raise Exception rescue nil
Run Code Online (Sandbox Code Playgroud)

但我发现的最短路径是:

begin
  raise Exception
rescue Exception
end
Run Code Online (Sandbox Code Playgroud)

Jon*_*rtz 28

这是由ActiveSupport提供的:

suppress(Exception) do
   # dangerous code here
end
Run Code Online (Sandbox Code Playgroud)

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

  • +1表示干净的解决方案,但我更喜欢无依赖项的解决方案。 (2认同)
  • 我建议将“ Exception”替换为“ StandardError”,因为[这不是挽救“ Exception”的好习惯]](/sf/ask/703372141/ -ruby-e-in-ruby)。 (2认同)

Zim*_*bao 27

def ignore_exception
   begin
     yield  
   rescue Exception
   end
end
Run Code Online (Sandbox Code Playgroud)

现在写代码为

ignore_exception { puts "Ignoring Exception"; raise Exception; puts "This is Ignored" }
Run Code Online (Sandbox Code Playgroud)


Saa*_*lik 9

只需将左侧包裹在括号中:

(raise RuntimeError, "foo") rescue 'yahoo'
Run Code Online (Sandbox Code Playgroud)

请注意,仅当异常是StandardError或其子类时才会进行救援.有关详细信息,请参阅http://ruby.runpaint.org/exceptions.