How to catch exceptions from constructor initializer list?

4 06 2008


C++ provides constructor initializer list to initialize member variables of type reference, const etc. In the constructor initialize list, we can initialize ordinary objects too. See sample below.

MyClass::MyClass( int var1, int var2 )
    : m_var1( var1 ),
      m_obj2( var1 ) // If this one throws an exception,
                     // it can't be caught.
{
    try
    {
       // Constructor body.
    }
    catch( ... )
    { }
}

But did you noticed that, these constructor initialize list is outside the function body, and if an exception is thrown from any of the member variable’s constructor, how it can be caught?


There is a special kind of try-catch usage to catch exceptions from constructor initialize list. See the code snippet below.

MyClass::MyClass( int var1, int var2 )
    try : m_var1( var1 ),
          m_obj2( var1 )    // Now I can catch the exception.
{
    // Constructor body.
}
catch( ... )
{ }

Now you can catch exceptions from constructor member initializer list also.


You cannot compile this in Visual C++ 6.0, since its does not strictly confirms C++ standards. You can compile this on Visual Studio 7.0 onwards.


Targeted Audience – Intermediate.