代码之家  ›  专栏  ›  技术社区  ›  Justin L.

如果没有一个空白的“rescue”块,Ruby块/命令就会自动失败

  •  12
  • Justin L.  · 技术社区  · 16 年前

    假设我想运行一个调用,如果失败了,那没什么大不了的;程序可以毫无问题地继续。(我知道这通常是不好的做法,但是想象一下一个假设的、快速的一次性脚本,而不是一个大项目)

    我被教导这样做的方式是:

    begin
      thing_to_try
    rescue
      # awkward blank rescue block
    end
    next_thing
    

    当然,还有其他方法可以做到这一点,包括使用 ensure 诸如此类的事情。但是有没有办法让方法调用/块在没有混乱的空白块的情况下自动失败呢?

    3 回复  |  直到 16 年前
        1
  •  13
  •   wuputah    16 年前

    像这样的方法是有帮助的。

    def squelch(exception_to_ignore = StandardError, default_value = nil)
      yield
    rescue Exception => e
      raise unless e.is_a?(exception_to_ignore)
      default_value
    end
    

    class Object 通用性。

    然后你可以写:

    squelch { foo } || squelch { bar }
    

    rescue 只能用于单个语句。

        2
  •  21
  •   Ben Hughes    16 年前

    thing_to_try rescue nil
    next_thing
    
        3
  •  1
  •   Nikita Rybak    16 年前

    除了 本 的想法,您还可以为此创建一个函数

    def suppress_errors(&block)
      begin
        yield
      rescue
        # awkward blank rescue block
      end
    end
    
    # call it    
    suppress_errors {puts "abc"}
    suppress_errors do
      puts "xyz"
    end