Posts tagged exceptions
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.
Catching exceptions from the constructor
0![]()
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.