Reraise (same exception) after catching an exception in Ruby Reraise (same exception) after catching an exception in Ruby ruby ruby

Reraise (same exception) after catching an exception in Ruby


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  raiseend

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.


This will raise the same type of error as the original, but you can customize the message.

rescue StandardError => e  raise e.class, "Message: #{e.message}"


A slightly better way to do the same thing as FreePender is to use the exception method from the Exception class, which is the ancestor class to any error classes, like StandardError, so that the method is available to any error classes.

Here the method's documentation that you can find on ApiDock:

With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to string.to_str.

Now let's see how it works:

begin  this_will_fail!rescue Failure => error  raise error.exception("Message: #{error.message}")end