From: Dave Mihalik Date: 2006-07-28T05:52:08+09:00 Subject: Re: Prevent class instantiation from the initialize method? >That said, using exceptions for control flow is usually a bit of > pathological case in Ruby, and there's usually a better way to > accomplish the same result. The two possible answers that spring to > mind are (simple) making the initialiser private or (slightly more > complicated) just removing the new method all together: 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. 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? -- Posted via http://www.ruby-forum.com/.