Within Ruby, what is the proper way of re-throwing caught (rescued)
exception?
Is just using ‘raise’ after a ‘rescue’ proper? See below two attempts to
re-throw exceptions just using ‘raise’:
begin
# Do stuff #
rescue ServiceException
raise
rescue SdkException
raise
rescue Exception => e
raise SdkException.new( "Failed to process request: %s: %s" %
You can re-raise the rescued exception by calling raise with the
argument being the Exception (or subclass) object.
E.g.:
begin
# Do stuff #
rescue ServiceException => e
raise e
rescue SdkException => e
raise e
rescue Exception => e
raise SdkException.new( "Failed to process request: %s: %s" %
[e.class, e.message] )
end
Alternatively (same function, but coded how I’d have written it):
begin
# Do stuff #
rescue Exception => e
raise e if e.is_a?(ServiceException) || e.is_a?(SdkException)
raise SdkException.new( "Failed to process request: %s: %s" %
While your exception code works, it’s not how you should use the “raise”
method in Ruby (you seem to be taking it from Java or so). The usual and
sensible way is
raise YourExceptionClass, ‘yourmessage’
This is less cumbersome and allows you to add additional arguments for
the call stack.
Apart from that, you should be very careful when rescuing Exception
objects. That’s the most basic class which includes severe system errors
you shouldn’t touch at all.
The only situation where this might make sense is if you want to catch
all errors on the top level to execute some special code.
While your exception code works, it’s not how you should use the “raise”
method in Ruby (you seem to be taking it from Java or so). The usual and
sensible way is
raise YourExceptionClass, ‘yourmessage’
This is true for raising, but he was asking about re-raising… in which
just calling raise is fine.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.