Hi,
when I rescue an exception, is there a way to access the object where
the exception was raised?
For example:
begin
"something".nonexistent
rescue NoMethodError => e
# here
end
In the rescue block, can I access the String "something"?
Best,
Florian
Not by default. According to
http://www.ruby-doc.org/ruby-1.9/classes/Exception.html
an exception provides "...information about the exception—its type
(the exception’s 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 = nil, source = nil)
super(msg)
@source = 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 = Test.new
puts t.enclose('foo')
puts t.enclose(5)
rescue MyException => 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