Exception Handling in Windows Message Loop
Posted on 2006-10-29
We have found something interesting out with an win32 C/C++ application (vc6 & vc8)and the message pump handling (in this case WM_TIMER).
A 3rd party dll could cause an exception without exception protection without the application crashing. In our case this was bad because the state of internal code became indeterminate because the DLL entry point did not have an exit point, i.e. the WM_TIMER called a function which crashed, then just called it again on the next timer.
Some sample code will follow which shows this behaviour :
>> The question is does anyone know of something definitive on why this behaviour is happening ? Under MSDN and elsewhere, we can't find any doco on message loop handling that references that it protects the function call from crashes .
To ensure that the call is "stateful" we will need to try / catch many code points within the WM_TIMER function .
Sample code :
//Timer callback function
void CALLBACK RecvTimer(HWND hwnd, UINT msg, UINT idTimer, DWORD dwTime)
char *test = NULL;
*test = 'a'; //Throw SEH exception (access violation)
//Initilise the timer
return SetTimer(NULL, 1199, 100, (TIMERPROC)RecvTimer);
void main( int argc, char** argv )
// create the dialog window
HWND hWnd = ::CreateDialog(NULL,
if ( hWnd!=NULL )
// show dialog
printf("Failed to create dialog\n");
//Initilise the timer.
printf("Failed to initilise timer\n");
// message loop to process user input
while (GetMessage(&msg, // message structure
NULL, // handle to window to receive the message
NULL, // lowest message to examine
NULL) // highest message to examine
!= 0 && GetMessage(&msg, NULL, NULL, NULL) != -1)
// Post WM_TIMER messages to the hwndTimer procedure.
if (msg.message == WM_TIMER)
msg.hwnd = hWnd;
TranslateMessage(&msg); // translates virtual-key codes
DispatchMessage(&msg); // dispatches message to window
/************************** end ************************/