+ 2

Exception in constructor

1. What are the example when we have exception in constructor? 2. Will destructor called for this object ? Assume few allocation done and those need to be deallocated in destructor... 3. Do i need to ask all user to create object of class in try catch ? No alternate mechanism as user might not create object within try catch

2nd Oct 2022, 8:43 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 8
1. Exceptions occur in constructors, just like it would occur in any other function body ( for example, failure to initialise objects, maybe due to insufficient memory ) 2. No, if a constructor throws before completing its body, the object is not considered constructed and hence no destructor would be called. Though memory allocated by new is automatically deallocated so ``` myclass *p = new myclass (); ``` Here, if the constructor failed, memory of *p will not leak. But, any memory allocated inside the constructor's body will leak ( that's why it's recommended to use smart pointers here ) 3. Throwing exceptions from constructor and handling them inside the caller's body should be the way to go. according to isocpp FAQ, the other option is to put the object in zombie state ( by setting some internal status bits ) and restructure class to detect and handle those objects. https://isocpp.org/wiki/faq/exceptions#ctors-can-throw
3rd Oct 2022, 1:13 AM
Arsenic
Arsenic - avatar
+ 3
If you don't like throwing constructors (and I can't blame you), another option is to create a factory method that throws, so that the constructor doesn't have to. Depends on the usecase of course.
3rd Oct 2022, 6:24 PM
Schindlabua
Schindlabua - avatar