Which is the shortest way to silently ignore a Ruby exception
我在找这样的东西:
1 | raise Exception rescue nil |
但我找到的最短的方法是:
1 2 3 4 | begin raise Exception rescue Exception end |
这由ActiveSupport提供:
1 2 3 | suppress(Exception) do # dangerous code here end |
http://api.rubyonrails.org/classes/kernel.html方法-i-suppress
1 2 3 4 5 6 | def ignore_exception begin yield rescue Exception end end |
现在将代码编写为
1 | ignore_exception { puts"Ignoring Exception"; raise Exception; puts"This is Ignored" } |
用括号括住左侧:
1 | (raise RuntimeError,"foo") rescue 'yahoo' |
请注意,只有当异常是一个标准错误或其子类时,救援才会发生。有关详细信息,请参阅http://ruby.runpaint.org/exceptions。