返回false与在Ruby中引发异常 - 何时以及为何?

Hom*_*ith 4 ruby exception-handling ruby-on-rails

我对以下概念感到困惑:

  • 不要将异常用作控制流
  • 不要将nil/false作为例外返回

假设我有以下实例方法:

class Logo
  # This method has some logic to create an image using Rmagick
  def process
    begin
      @logo_image = RmagickHelper.new(self.src)
    rescue Magick::ImageMagickError
      raise Exceptions::LogoUnprocessable, "ImageMagick can't process the URL"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

因此,在更通用的方法中,我有以下内容:

def build_all_images
    begin
      @logo.process
    rescue Exceptions::LogoUnprocessable
      @logo.status = 'unprocessable'
      return false #This terminates the method so no more stuff is processed, because logo could not be processed.
    end
#....
end
Run Code Online (Sandbox Code Playgroud)

我的问题是:

这样做是否正确:

raise Exceptions::LogoUnprocessable, "ImageMagick can't process the URL"
Run Code Online (Sandbox Code Playgroud)

或者我应该刚做完

return false
Run Code Online (Sandbox Code Playgroud)

Uri*_*ssi 7

曾几何时,有一种没有异常结构的语言().每条消息返回一个整数 - 0表示成功,或者一些错误代码表示失败.如果来电者在继续之前没有检查返回代码 - 他会被搞砸.此外,大多数的时间调用者没有任何关系,他可以做有关失败的,所以即使他做了检查,结果-他唯一的聪明的事情可以做的是回到了自己的错误代码......

然后是,带有异常结构,仅用于这些用例.对于方法陷入无法处理的情况(例如,读取不存在的文件,或没有网络连接的网上冲浪),会出现例外情况.

滥用Exception构造意味着在完全预期的情况下引发异常,例如:

def even?
  if (self % 2 != 0)
    raise NumberNotEvenException
  end
end
Run Code Online (Sandbox Code Playgroud)

在这里,一个奇数是合法的,并且是预期的; 抛出错误是滥用异常构造.

当方法无法履行承诺时,抛出异常.

在另一面-返回nilfalse当一个方法失败使我们又回到了快乐的天,它是调用者的注意失败,并找出了问题的负担-不好玩.