Posts tagged catch(…)

How to catch exceptions from constructor initializer list?

4


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.

Use throw; carefully. Or else, Unhandled exception will be the result.

0


Usually throw; is used to rethrow the exception object. But you should be careful. If you call throw; where there is no exception object in the context, then it will result an un-handled exception and abnormal program termination. The interesting part is that, even catch(…) cannot catch such exceptions.


See the sample code snippet below.

try
{
    throw;
}
catch( ... )
{
}

So take care next time.


Targeted Audience – Intermedite.

Go to Top