Structured exception handling (SEH) is a useful set of functionality included in the Win32 API that lets C code handle errors in your application in much the same way that C++ handles exceptions. (To learn more about exception handling with C++ code, read the Win32 software development kit—SDK—topic "Using Structured Exception Handling with C++."
Exception handling in C consists of three blocks: try, finally, and except. You encase any code for which you want to handle exceptions in a __try block; any code you place in a __finally block always executes no matter how you exit the __try block; and the __except block lets you customize how you handle exceptions. Let’s look at a quick example.
void foo(char* arg)
{
char buf[30];
char* buf2;
__try
{
strcpy(buf, arg);
buf2 = malloc(30);
strcpy(buf2, arg);
}
__except( MyHandler( GetExceptionCode() ))
{
printf( "Ended up in the handler - whoops!\n" );
}
__finally
{
if( buf2 != NULL )
free( buf2 );
}
}
If an exception occurs while any of the code in the __try block is executing, the OS starts looking for an exception handler. Because most code doesn’t have its own exception handler, the stack unwinds until you hit the handler that the OS puts around your application for you, and you see the familiar pop-up message telling you that your application has an unhandled exception at a certain address. I provided a handler in the code example, and the next code to execute will be your MyHandler() function, which takes the exception code as an int, and is expected to return an int. There are three possible returns: . . .
Seth June 21, 2004