Forum: Ruby how best to handle errors in object instaintiation (sp ?)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Russell F. (Guest)
on 2005-12-06 03:23
Hi,
   I'm new to Ruby and still trying to figure out how best to do things
"the Ruby way".  The particular problem I am looking at now is the
initialize method of a class I am writing. Several things can go wrong
in calls to new for this class ranging from the caller specifying
incompatible parameters to database calls failing.

What is the perferred method of handling such errors? Simply raising
exceptions and returning nil?

Cheers, Russell
Timothy H. (Guest)
on 2005-12-06 04:08
(Received via mailing list)
Russell F. wrote:
> Cheers, Russell
>


You don't really have any choice. The return value from 'new' is an
instance of the class, never nil. (Okay, some clever Rubyists could
think of a way to make it nil, but no user of your class should ever be
asked to handle that case.) If your initialize method can fail, it
should raise an exception.
Russell F. (Guest)
on 2005-12-06 04:33
tim-hunter wrote:
> You don't really have any choice. If your initialize method can fail, it
> should raise an exception.

Great, that's what I thought but I wanted to make sure.  None of the
examples I found in books handled errors in new().

Thanks Tim.
halostatue (Guest)
on 2005-12-07 07:22
(Received via mailing list)
On 12/5/05, Timothy H. <removed_email_address@domain.invalid> wrote:
> You don't really have any choice. The return value from 'new' is an
> instance of the class, never nil. (Okay, some clever Rubyists could
> think of a way to make it nil, but no user of your class should ever be
> asked to handle that case.) If your initialize method can fail, it
> should raise an exception.

Hm, no, that's not quite right ;)

  class Foo
    def self.new
      super
    rescue Exception
      nil
    end
    def initialize
      raise "Bah!"
    end
  end

It's not ideal, and it would probably be better to do something like:

  class Bar
    class << self
      private :new

      def create(*args, &block)
        ob = self.allocate
        ob.initialize(*args, &block)
        ob
      rescue Exception
        nil
      end
    end
    def initialize(*args, &block)
      raise "Empty!" if args.empty
      @args = args
    end
    attr_accessor :args
  end

That is, it's better to use a different method than new.

-austin
This topic is locked and can not be replied to.