c++ – Handling Exceptions in Class Constructors


What's the point of using a try catch block where the try is in front of the constructor's initialization list if in the catch block we still throw the exception up? Sample code:

 class A{
      try : obj(123){
     SomeType obj;

 int main(){
    A* obj;
         obj = new A; 

The point is for me to write a try catch block for the constructor, if the exception goes into the outer trycatch anyway. I have only one option: the trycatch for the constructor can pass up its own type of exception, which we want. No more options


One of the options for using such a "mediator" can be to reduce all exceptions thrown from subclasses and non-static data to a single type of exception:

class SomeTypeExp
template<typename ... Classes>
struct SomeType: Classes...
    SomeType() try {
    } catch (SomeTypeExp const & e) {
        throw e;
    } /*...*/
    catch (std::exception const & e) {
        throw make_some_expr(e);//return SomeTypeExp object
    }catch (...) {
        throw SomeTypeExp("Unknown");
    //Other members

For this code, no matter what exceptions are thrown when creating an object, an exception of the SomeTypeExp type will be thrown "up". This means that "at the top" it is necessary to catch and handle only it, and not all possible types of exceptions. You can also add a message to the log or perform some actions, but you cannot access non-static class members from this block, since the object has already been destroyed, and this is clearly visible if an exception flew out of the delegating constructor after the non-delegating constructor has successfully worked.

You can read more about function-try-block for functions, destructors and constructors: http://pcdev.ru/function-try-block/

Scroll to Top