【问题标题】:Which is the shortest way to silently ignore a Ruby exception这是静默忽略Ruby异常的最短方法
【发布时间】:2011-07-02 15:59:58
【问题描述】:

我正在寻找这样的东西:

raise Exception rescue nil

但我发现的最短方法是:

begin
  raise Exception
rescue Exception
end

【问题讨论】:

    标签: ruby exception-handling


    【解决方案1】:
    def ignore_exception
       begin
         yield  
       rescue Exception
       end
    end
    

    现在把你的代码写成

    ignore_exception { puts "Ignoring Exception"; raise Exception; puts "This is Ignored" }
    

    【讨论】:

    • 注意(因为我一开始误解了):这“忽略”了异常,因为在跳过开始和救援异常之间的其余部分之后一切都会继续。它没有做的是完全忽略异常,因为它继续做它在开始和救援之间所做的事情。
    【解决方案2】:

    这是由 ActiveSupport 提供的:

    suppress(Exception) do
       # dangerous code here
    end
    

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

    【讨论】:

    • +1 表示干净的解决方案,但我更喜欢无依赖的解决方案。
    • 我建议将 Exception 替换为 StandardError,因为 it's not a good practice to rescue Exception
    • 干净吗?在我看来,这是最愚蠢的方法,它以另一种方式重写了相同的东西,但在大多数情况下,它甚至不比简单的 rescue Exception; end
    • 越短并不总是越好。在这种情况下,意图比滚动到块的末尾并看到“救援结束”要清楚得多。
    【解决方案3】:

    只需将左侧括在括号中:

    (raise RuntimeError, "foo") rescue 'yahoo'
    

    请注意,只有当异常是 StandardError 或其子类时才会发生救援。请参阅http://ruby.runpaint.org/exceptions 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多