Returns false vs, throwing an exception in Ruby. When and why?

I am really confused in terms:

  • Do not use exceptions as a control flow.
  • Do not return nil / false as an exception

Let's say I have the following instance method:

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

So, in a more general method, I have the following:

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

My question is:

Is it right to do this:

raise Exceptions::LogoUnprocessable, "ImageMagick can't process the URL"

Or should I just do

return false
+4
source share
2 answers

- (c). - 0 . , , . , , , - , , ...

++, , . , , (, , , ).

Exception , , :

def even?
  if (self % 2 != 0)
    raise NumberNotEvenException
  end
end

, , ; - .

, , .

- nil false, c , , , - .

+7

, .

" url", "" , , URL-, .

"" . , " ", "oops!"

- " ", "oops" .

, , - , .

+3

Source: https://habr.com/ru/post/1541670/


All Articles