Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!rutgers!bellcore!faline!ulysses!allegra!alice!shopiro From: shopiro@alice.UUCP Newsgroups: comp.lang.c++ Subject: Re: Handling errors in constructors Message-ID: <7188@alice.UUCP> Date: Mon, 17-Aug-87 12:13:25 EDT Article-I.D.: alice.7188 Posted: Mon Aug 17 12:13:25 1987 Date-Received: Tue, 18-Aug-87 06:20:44 EDT References: <10024@duke.cs.duke.edu> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 30 Keywords: errors, constructors Summary: create a dead object In article <10024@duke.cs.duke.edu>, rjn@duke.UUCP writes: > > Does anyone have any really good ideas on handling errors in constructors? > If an object is made using a new call: > foo = new class; > then it is fairly easy to signal an error by returning NULL from the > constructor. ... > The problem comes when objects are allocated on the stack: > class foo; > Then the memory for the object is on the stack. ... My rule is that if the constructor returns at all, it must create a legitimate object. If there is a possibility for the constructor to fail, then indication of the failure is stored in the object. I provide such objects with member functions to interrogate their status, and other member functions check the status and try to do something appropriate if they can't do their intended function. I think an error handler which is an inherited static member is fine, but it generally is only useful for logging error messages. If you are building classes to use yourself, then more or less anything goes, but if you are building classes for others to use, then the approach of always creating an object seems cleanest to me. Returning NULL from a constructor is not a good idea at all. Assignments to `this' will soon be deprecated. (Don't worry, a better alternative is coming). -- Jonathan Shopiro AT&T Bell Laboratories, Murray Hill, NJ 07974 research!shopiro (201) 582-4179