On Tue, Apr 1, 2008 at 7:21 PM, Hartin, Brian <Brian.Hartin / pearson.com> wr=
ote:
> I could not find any information about this, except regarding DRb.
>
> It seems like the raise method / Exception class ought to allow me to
> pass in a 'causal' exception, e.g.

Why?  This is a feature most needed by languages with checked exceptions.

> begin
> =A0foo
> rescue Exception =3D> e
> =A0raise ServiceNotFoundException, "The service could not be contacted",
> e
> end
>
> This doesn't work. =A0I can, however, pass in the backtrace, e.g.
>
> raise ServiceNotFoundException, "The service could not be contacted",
> e.backtrace
>
> However, doing this I get the stack trace but not the type or message
> from the causal exception (unless I manually put them in the message
> string). =A0Ideally, I'd be able to use exception chaining such as in
> Java, in which my stack traces include causal exceptions:
>
> WebServiceCommunicationException: The WSDL could not be obtained from
> http://blah/wsdl.
> =A0from (webservice_client.rb):123:in `obtain_wsdl'
> =A0from (webservice_client.rb):12:in `request_price'
> caused by ParsingError: Unexpected element 'html'
> =A0from (other_class.rb):234 in 'some_method'
> =A0from (other_class.rb):23 in 'some_other_method'
> =A0...
>
> including a 'cause' field on the Exception class, e.g. e.cause.
>
> Is there some reason why this would not fit the Ruby style? =A0If not, is
> this something that would be considered as a patch/change for Ruby?

Ruby does not have checked exceptions and it provides enough
mechanisms to deal with exceptions which make wrapping superfluous
(see below).

> I realize I could probably monkeypatch Exception, but this seems (to me)
> like it would be an improvement to the language.

It may be - but not a big one.  I would not do it.

If you cannot handle the exception, don't catch it =3D> no need for
wrapping.  If you need to cleanup in all cases you can use "ensure"
(like "finally" in Java) =3D> no need for wrapping exceptions either.
If you need to do some cleanup in case of exception only, you can use
"raise" without arguments:

10:31:20 ~$ ruby19 <<CODE
> def f
> raise "Ex 1"
> end
> def g
> f
> rescue Exception =3D> e
> printf "Caught %p\n", e
> raise # reraises
> end
> begin
> g
> rescue Exception =3D> e
> printf "Main caught %p\n", e
> puts e.backtrace
> end
> CODE
Caught #<RuntimeError: Ex 1>
Main caught #<RuntimeError: Ex 1>
-:2:in `f'
-:5:in `g'
-:11:in `<main>'
10:32:53 ~$

DRb really seems the only place where a kind of wrapping may make
sense but even here you probably do not want to wrap exceptions but
just carry over backtraces, because the exception class may not be
known to the client.

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/