From: Alex Young Date: 2006-07-28T08:07:38+09:00 Subject: Re: Prevent class instantiation from the initialize method? Dave Mihalik wrote: > I am trying to determine how my program should handle errors in the > initialize method. If an error occurs in code that is running in the > initialize method, I want to be able to prevent the class from > instantiating. It depends on the nature of the code that can fail, and what *exactly* you mean by "instantiating". This might work, if the failable code is relevant outside an instance: class TestClass def TestClass.get_new(params) begin settings = do_work_that_can_fail(params) new(settings) rescue puts "Waaah! It didn't work!" nil end end end If that's not appropriate, then there's this: class TestClass def TestClass.get_new(params) begin new(params) rescue puts "Still didn't work!" nil end end def initialize(params) do_work_that_can_fail(params) end end In the second case (unless I'm mis-remembering how the object lifecycle works) the instance is created in the new() call, but it'll get disposed of in the next GC round because there aren't any references to it being held anywhere. In both cases, you just call TestClass.get_new() rather than TestClass.new() to get your instance, or nil if the stuff that can fail fails. -- Alex > > > class Testclass > def initialize() > > ## Do work here. > ## Do more work here. > ## Get an error from doing more work. > > ## Raise an error to prevent the class from instantiating because > ## the functionality of the class depends on the above work. > > ##raise "Instantiation cancelled." > > end > end > > ## Try to instantiate the class. > begin > > mytest = Testclass.new() > > ## Make sure that the instantiation was successful. > rescue Exception => e > > ## If not, handle the error. > puts e > exit 1 > > end > > ## If instantiation succeeded, then proceed with the program. > puts "Instantiation not cancelled." > > Is there a better way to handle errors in the initialize method? >