How to catch exceptions from constructor initializer list?
![]()
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.
It is quite cool…
I was not knowing about it…
Thanks for the info…
There are many pearls inside C++.
You should not use this for several reasons:
- First of all is not c++ standard
- Secondly if you capture and exception in the initialiser list obviously your object is not properly constructed, how do you inform the calle of this?, as constructors do not have return values, the only clean method of doing this is throwing the exception for the callee to capture and do something about it.
There is no problem with function level try-catch blocks, as the invoker of the constructor will get to know about the failure of it, because here the catch block will going to re-throw the exception for the caller to handle. Catch block just helps in doing any exception conversion or necessary action to be performed before leaving constructor body.
Moreover if any of the sub-object is already created when exception occurred, language ensures that already created objects destructor are invoked.