How best to handle errors in object instaintiation (sp ?)


#1

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


#2

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.


#3

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.


#4

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 :wink:

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