Catching exceptions from the constructor’s member initialize list.

8 04 2008


In constructors we initialize member variables by using member initialize list. The initialize list is out of constructors function body and how the exception thrown by members in initialize list can be caught by try-catch? See the code block.

class MyClass
{
public:
MyClass( int var1, int var2 )
: m_var1( var1 ),
m_obj2( var1 ) // If this one throws an exception, i can't catch it.
    {
        try
        {
           // Constructor body.
        }
        catch( … )
        { }
    }
int m_var1;
    CMyObject m_obj2;
};

Here if m_obj2 throws an exception, it cannot be catch by the try-catch block, because the initialize list is outside the try-catch block.


For catching exceptions from the initialize list, there is a special type of try-catch pattern. See the code block.

class MyClass
{
public:
    MyClass( int var1, int var2 )
    try : m_var1( var1 ),
          m_obj2( var1 )    // Now I can catch the exception.
    {
       // Constructor body.
    }
    catch( ... )
    { }
// Member variables.
    int m_var1;
    CMyObject m_obj2;
};


If you compile it in Visual Studio 6.0 it will show a couple of errors. Try next versions such as Visual Studio 2005, etc.


Targeted Audience – Intermediate.

Advertisements