From: Timothy Hunter Date: 2006-10-06T21:50:49+09:00 Subject: Re: Should a Class return an exception or nil on failure to create? _Kevin wrote: > Suppose I've written a class that does something useful. > > This class, let's call it a Widget, is created like this... > > a = Widget.new(some_value) > > Not all values of 'some_value' are valid and I need to indicate when > creation fails. > I see two ways to signify this... > > a = Widget.new(invalid_value) #=> nil > or > a = Widget.new(invalid_value) #=> raises an exception > > Which of these do you prefer and why? > > Would you prefer both? How about a 'Widget.new!' method that throws an > exception? > > Thanks, > _Kevin > > > Exception. It's not really a matter of preference. YourClass.new allocates an instance of your class and then calls initialize on the new instance. YourClass.new will return the new instance unless initialize raises an exception. Now some advanced Rubyists out there will jump in and explain how to subvert the allocate/initialize process but you're asking about the "usual" case, right?