Professional Documents
Culture Documents
Exception Handling
Exception Handling
SEH
SEH stands for structured Exception Handling.
Advantages of SEH
You can deallocate resources in case of error instead of leaving
it to the OS.
1. EXCEPTION_EXECUTE_HANDLER
2. EXCEPTION_CONTINUE_SEARCH
This tells to not execute the first except block and pass it to
search for the next except block.
3. EXCEPTION_CONTINUE_EXECUTION
REMEMBER!
Example:
Termination Handler
A termination handler serves much the same purpose as an
exception handler, but it is executed when a thread leaves a
block as a result of normal program flow as well as when an
exception occurs.
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
_tprintf(_T("Parent Exception\n"));
}
Output
First try
Second try
finally
parent Exception
Output
As exception raises it will go to find the exception handle it
come across the custom exceptional handler method
FilterFunction() which gets executed and return the
EXCEPTION_EXECUTE_HANDLER which says go execute your
finally first and come back then the rest __except code gets
executed.
Output
Output
Output
6. What will be the output of the
following code?
DWORD FilterFunction()
{
printf("1 "); // printed
first
return EXCEPTION_EXECUTE_HANDLER;
}
int _tmain(int argc, LPTSTR argv[])
{
__try
{
__try
{
__try
{
RaiseException(
1, //
exception code
0, //
continuable exception
0, NULL); // no
arguments
printf("after raising exception\n");
}
__finally
{
printf("2 "); // this is
printed second
}
}
__except (EXCEPTION_CONTINUE_EXECUTION)
{
printf("3\n"); // this is
printed last
}
}
__except (FilterFunction())
{
printf("4\n"); // this is
printed last
}
return 0;
}
Output
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
_tprintf(_T("Parent Exception\n"));
}
Output
Error
Error because You can't have both except as well as finally for
a single __try.
Output
Error
You can't have a try without except and __finally, you need to
have one of them.
int i;
Output
__try is attached to the for loop. We can say that the entire for
loop body is inside the __try.
if (exceptionCode != 0)
RaiseException (
(0x0FFFFFFF & exceptionCode) |
0xE0000000, 0, 0, NULL);//E for error
return;
}
For example:
The 2 will set the 29th bit to 1 and doing and with exCode will
let us know it's the user exception or not.