Re-throwing an exception

Hi

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" %
[e.class, e.message] )
    end

Thanks

- Jeff in Seattle

···

--
Posted via http://www.ruby-forum.com/.

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" %
[e.class, e.message] )
     end

-- Matma Rex

this works too:
  begin
  # Do stuff #
  rescue ServiceException,SdkException
    raise
  end

···

--
Posted via http://www.ruby-forum.com/.

Hi,

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.

http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-raise

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.

···

--
Posted via http://www.ruby-forum.com/.

Thank you for the reply

-- Jeff in Seattle

···

--
Posted via http://www.ruby-forum.com/.

This is true for raising, but he was asking about re-raising... in which just calling raise is fine.

···

On Sep 20, 2012, at 14:21 , Jan E. <lists@ruby-forum.com> wrote:

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'