Mixing SEH and C++ exceptions in VC++

I think you are familiar with windows Structured Exception Handling(SEH).
In simple words it is used to catch exceptions raised by Windows itself. __try/__except keyword is used here.C++ language has also it’s own exceptions mechanism(using normal try/catch).

Exception

In Visual Studio you can manage exception mechanism by going Project Property –>Configuration property–>C/C++–>Code Generation –>Enable C++ Exception option as shown below;

SEH-1

By default Enable C++ Exception will be set to (Yes (/EHsc) option).
with this settings when a c++ exception is thrown stack unwinding will happen and destructors of the local class in try block will be executed.But with this settings when a SEH exception is thrown stack unwinding is not happening and so destructors of the local objects in the _try block will not be executed.
This is a memory leak. To avoid this you can change the exception settings to (Yes with SEH Exceptions (/EHa)) as shown below.Wit this settings stack unwinding happens both in C++ and SEH exceptions.

SEH-2

Following example shows this,run the example with /EHsc and /EHa options to see the difference.


// TestSEH.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include <Windows.h>
#include <exception>
using namespace std;
class CLocalClass
{

public:
	CLocalClass(){   cout<<"\nInside Constructor";}
	~CLocalClass() { cout<<"\nInside Destructor"; }

};

void Test() 
{
	CLocalClass obj;
	int * ptr = NULL;
	//throw std::exception("C++ Exception"); 
	*ptr = 100;
}

int _tmain(int argc, _TCHAR* argv[])
{
	__try{

		Test();

	}__except(EXCEPTION_EXECUTE_HANDLER)
	{
		cout<<"\nInside __except";
	}
	return 0;
}


Entire Project using VS 2010 can be downloaded from link:Download