What am I doing wrong here? This little test program is based on the
example on p. 97 in the Pickaxe:
class MyError < StandardError
def initialize(loc)
@extra = loc
end
def extra
@extra
end
end
def read_file(name)
raise MyError.new(“line 1”), "Unable to read file: #{name}"
end
begin
read_file(‘foo.jpg’)
rescue MyError => error
puts "error=#{error}"
puts "error.extra=#{error.extra}"
end
I expect the 2nd puts to print “line 1”. However, the output is:
[tim:~]$ ruby test.rb
error=MyError
error.extra=Unable to read file: foo.jpg
This is Ruby 1.6.8.
ts1
(ts)
2
This is Ruby 1.6.8.
Well, for 1.6.8 see [ruby_talk:36408]
http://www.ruby_talk.org/36408
Guy Decoux
Tim Hunter wrote:
What am I doing wrong here? This little test program is based on the
example on p. 97 in the Pickaxe:
raise MyError.new("line 1"), "Unable to read file: #{name}"
begin
read_file(‘foo.jpg’)
rescue MyError => error
puts “error=#{error}”
puts “error.extra=#{error.extra}”
end
I expect the 2nd puts to print “line 1”. However, the output is:
[tim:~]$ ruby test.rb
error=MyError
error.extra=Unable to read file: foo.jpg
This is Ruby 1.6.8.
Interestingly, this works on 1.8, but not on 1.6.8. An approach that
works for both is:
class MyError < StandardError
def initialize(loc, msg)
super(msg)
@extra = loc
end
def extra
@extra
end
end
def read_file(name)
raise MyError.new(“line 1”, “Unable to read file: #{name}”)
end
begin
read_file(‘foo.jpg’)
rescue MyError => error
puts “error=#{error}”
puts “error.extra=#{error.extra}”
end
Cheers
Dave
Hi,
def read_file(name)
raise MyError.new(“line 1”), “Unable to read file: #{name}”
Kernel#raise calls #exception method of the first argument with
the rest, and throws the result.
In 1.6, Exception#exception creates new instance of the class
of self, but in 1.8 just sets mesg and backtrace to a clone.
revision 1.34
date: 2001/11/13 08:19:51; author: matz; state: Exp; lines: +2 -2
- error.c (exc_exception): set “mesg” directly to the clone. it
might be better to set mesg via some method for flexibility.
···
At Tue, 15 Jul 2003 22:17:11 +0900, Tim Hunter wrote:
–
Nobu Nakada