Adding Information to Exceptions

T

Tim Hunter

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.
 
N

nobu.nokada

Hi,

At Tue, 15 Jul 2003 22:17:11 +0900,
Tim said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top