On 28 Juli, 10:54, Florian Odronitz <o... / mac.com> wrote:
> Hi,
>
> when I rescue an exception, is there a way to access the object where
> the exception was raised?
>
> For example:
>
> begin
> =A0 "something".nonexistent
> rescue NoMethodError =3D> e
> =A0 # here
> end
>
> In the rescue block, can I access the String "something"?
>
> Best,
> Florian
> --
> Posted viahttp://www.ruby-forum.com/.

Not by default. According to http://www.ruby-doc.org/ruby-1.9/classes/Excep=
tion.html
an exception provides "...information about the exception=97its type
(the exception=92s class name), an optional descriptive string, and
optional traceback information..."

However the same page also says "...Programs may subclass Exception to
add additional information."

So, if your roll your own exceptions it's possible to add this
functionality.

class MyException < Exception

  attr_accessor :source

  def initialize(msg =3D nil, source =3D nil)
    super(msg)
    @source =3D source
  end
end

class Test
  def enclose(obj)
    if obj.kind_of?(String)
      "(#{obj})"
    else
      raise MyException.new('Enclose needs a string!', obj)
    end
  end
end

begin
  t =3D Test.new
  puts t.enclose('foo')
  puts t.enclose(5)
rescue MyException =3D> err
  puts "Error: #{err.message}"
  puts "Source: #{err.source}"
end

Overriding the default Exception class might also be possible (after
all, it's ruby) but changing "default" behavior can be pretty risky as
well.

/lasso