Monday, March 29, 2010

Exception Handing

What is the output of the following program?

CRITICAL_SECTION g_cs;

int filter(unsigned int code, struct _EXCEPTION_POINTERS *ep)
{
OutputDebugStringA("Inside Filter Function");
if (code == EXCEPTION_ACCESS_VIOLATION)
{
return EXCEPTION_EXECUTE_HANDLER;
}
else
{
return EXCEPTION_CONTINUE_SEARCH;
}
}


int _tmain(int argc, _TCHAR* argv[])
{
__try
{
__try
{
__try
{
EnterCriticalSection(&g_cs);
}
__finally
{
OutputDebugStringA("inner\n");
}
}
__finally
{
OutputDebugStringA("outer\n");
}
}
__except(EXCEPTION_EXECUTE_HANDLER/*filter(GetExceptionCode(), GetExceptionInformation())*/)
{
OutputDebugStringA("Got the exception\n");
}

return 0;
}

Answer:

Inside Filter function
Inner
Outer
Got the exception

Summary:

Whenever exception happens it searches for very first __except irrespective of any number of __finally block in between(like above) and then it executes very first finally block and soon...

Why exception has occurred in above code?
Ans: We have not called InitializeCriticalSection().

No comments:

Post a Comment