Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!seismo!rutgers!mcnc!duke!rjn From: rjn@duke.cs.duke.edu (R. James Nusbaum) Newsgroups: comp.lang.c++ Subject: Handling errors in constructors Message-ID: <10024@duke.cs.duke.edu> Date: Mon, 10-Aug-87 15:33:17 EDT Article-I.D.: duke.10024 Posted: Mon Aug 10 15:33:17 1987 Date-Received: Tue, 11-Aug-87 05:39:36 EDT Reply-To: rjn@duke.UUCP (R. James Nusbaum) Organization: Duke University, Durham NC Lines: 35 Keywords: errors, constructors 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, although you should be careful about cleaning up any memory that may have been automatically allocated by the constructor. Since I usually do custom memory allocation for objects, this isn't too much of a problem. The problem comes when objects are allocated on the stack: class foo; Then the memory for the object is on the stack. My constructors are often fairly complicated (creating sockets, allocating memory). If an error occurs in the constructor and the object is on the stack I have to come up with some way of alerting the user that an error has occured immediately, and not wait for a segmentation fault to occurr later. Now I do have one solution. All my classes have built in error logging using a global structure (implemented as an inherited static member) that acts something like the errno facility in Unix. The user can turn on debugging so that an error handling function is always called when an error has occured. The problem is that the user has to somehow turn on debugging before any objects are created, which can be very kludgy to do, and that constructor errors should be able to be caught separately since they are almost always fatal. To deal with this I have my constructors send a signal (one of the user defined ones) to the process when there is an error. If the user has made no arrangements to catch the signal then the program will terminate, or the user can set up a signal handler and perform whatever actions they desire. Any other suggestions? R. James Nusbaum, Duke University Computer Science Department, Durham NC 27706-2591. Phone (919)684-5110. CSNET: rjn@duke UUCP: {ihnp4!decvax}!duke!rjn ARPA: rjn@cs.duke.edu