Search code examples
rubyexception

Reraise (same exception) after catching an exception in Ruby


I am trying to improve my Ruby skills by catching exceptions. I want to know if it is common to reraise the same kind of exception when you have several method calls. So, would the following code make sense? Is it ok to reraise the same kind of exception, or should I not catch it on the process method?

class Logo
  def process
    begin
      @processed_logo = LogoProcessor::create_image(self.src)
    rescue CustomException
      raise CustomException
    end
  end
end

module LogoProcessor
  def self.create_image
    raise CustomException if some_condition
  end
end

Solution

  • Sometimes we just want to know an error happened, without having to actually handle the error.

    It is often the case that the one responsible for handling errors is user of the object: the caller. What if we are interested in the error, but don't want to assume that responsibility? We rescue the error, do whatever we need to do and then propagate the signal up the stack as if nothing had happened.

    For example, what if we wanted to log the error message and then let the caller deal with it?

    begin
      this_will_fail!
    rescue Failure => error
      log.error error.message
      raise
    end
    

    Calling raise without any arguments will raise the last error. In our case, we are re-raising error.

    In the example you presented in your question, re-raising the error is simply not necessary. You could simply let it propagate up the stack naturally. The only difference in your example is you're creating a new error object and raising it instead of re-raising the last one.