Adding Information to Exceptions

Discussion in 'Ruby' started by Tim Hunter, Jul 15, 2003.

  1. Tim Hunter

    Tim Hunter Guest

    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.
     
    Tim Hunter, Jul 15, 2003
    #1
    1. Advertising

  2. Tim Hunter

    ts Guest

    ts, Jul 15, 2003
    #2
    1. Advertising

  3. Tim Hunter

    Guest

    Hi,

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

    --
    Nobu Nakada
     
    , Jul 15, 2003
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ahmed Moustafa
    Replies:
    5
    Views:
    30,129
    Chris Smith
    Jul 14, 2004
  2. Paul Miller
    Replies:
    3
    Views:
    1,070
    Alex Martelli
    Nov 12, 2003
  3. Replies:
    1
    Views:
    349
    Steve Holden
    Oct 7, 2005
  4. Replies:
    3
    Views:
    637
    Sherm Pendley
    Apr 16, 2007
  5. Lie
    Replies:
    3
    Views:
    715
Loading...

Share This Page