From: Chris Hulan on
On Apr 6, 11:56 am, Brian Candler <b.cand...(a)pobox.com> wrote:
> Chris Hulan wrote:
> > The default Exception:initialize is defined to take 1 parameter, a
> > string containing the error message
>
> But 'raise' also lets you pass an error message, in addition to the
> exception instance.
>
> Note that even the default constructor doesn't create an instance
> variable called @message.
>
> class Foo < StandardError
> end
>
> begin
>   raise Foo, "bar"
> rescue Foo => e
>   p e
>   p e.instance_variables
>   p e.instance_variable_get(:@message)
>   p e.message
>   p e.backtrace
> end
>
> #<Foo: bar>
> []              # << No instance variables!
> nil             # << No @message!
> "bar"
> ["ert.rb:5"]
> --
> Posted viahttp://www.ruby-forum.com/.

I should stop answering questions based on reading the docs at ruby-
docs.org, they are just not very clear...plus sloppy reading on my
part doesn't help ;)
So message is not an attribute so using @message is wrong.
It looks like overriding to_s, or maybe using super in the override of
message to get the parents input.

cheers
From: Leslie Viljoen on
[Note: parts of this message were removed to make it a legal post.]

On Tue, Apr 6, 2010 at 7:10 PM, Chris Hulan <chris.hulan(a)gmail.com> wrote:

>
> I should stop answering questions based on reading the docs at ruby-
> docs.org, they are just not very clear...plus sloppy reading on my
> part doesn't help ;)
> So message is not an attribute so using @message is wrong.
> It looks like overriding to_s, or maybe using super in the override of
> message to get the parents input.
>
>
Yip, these surprising revelations were the reason for my post!

From: Leslie Viljoen on
[Note: parts of this message were removed to make it a legal post.]

On Tue, Apr 6, 2010 at 5:24 PM, Brian Candler <b.candler(a)pobox.com> wrote:

> Judging by the C source, Exception uses hidden(*) instance variables
> "mesg" and "bt" for message and backtrace respectively. However, the
> accessor #message internally calls #to_s, which you can override.
>
> class BillRowError < StandardError
> def initialize(field, index)
> @field = field
> @index = index
> end
>
> alias :orig_to_s :to_s
> def to_s
> "#{orig_to_s} field: #{@field}, row: #{@index}"
> end
> end
>
> begin
> raise BillRowError.new(5, 7), "bar"
> rescue BillRowError => e
> p e
> p e.instance_variables
> p e.message
> p e.backtrace
> end
>
> Produces:
>
> #<BillRowError: bar field: 5, row: 7>
> ["@index", "@field"]
> "bar field: 5, row: 7"
> ["ert.rb:14"]
>
> Admittedly this behaviour doesn't seem to be well documented, so may be
> fragile. Use at your own risk.
>
>
Wow thanks for this, I didn't think of aliasing the old to_s. I find it
strange that exceptions don't just use a plain old @message instance
variable but I suppose there's some good reason for it.


--
Do not support Microsoft:
http://www.vanwensveen.nl/rants/microsoft/IhateMS.html