Exception handling in Constructor
-
Hi Make the constructors private, then create a static member function called InitYourObject().
CYourClass * CYourClass::InitYourObject() { try { CYourClass *object = new CYourClass; return object; } catch(...) { //handle the error return NULL; // or throw exception } }
To create an object call CYourClass *myObject = CYourClass::InitObject(); Hope it helps RegardsThe Best Religion is Science. Once you understand it, you will know God.
-
I avoid putting error handing in the constructor (short of the occasional ASSERT). The constructor is for constructing. If there's a possibility of bad/invalid data, you should either allow the construction to happen and set appropriate conditions in the object to indicate invalid data, or you should validate data BEFORE construction so you can assume that everything is okay at the time of construction. I feel it makes the code much more maintainable (with appropriate and copious code comments of course). Of course, this is just the way I do it and I'm sure others will want to argue their own approach. You guys have fun with that.
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001 -