Platform SDK: Debugging and Error Handling |
The following example shows how a termination handler is used to ensure that resources are released when execution of a guarded body of code terminates. In this case, a thread uses the EnterCriticalSection function to wait for ownership of a critical section object. When the thread is finished executing the code that is protected by the critical section, it must call the LeaveCriticalSection function to make the critical section object available to other threads. Using a termination handler guarantees that this will happen.
For more information, see critical section objects.
LPTSTR lpBuffer = NULL; CRITICAL_SECTION csCriticalSection; __try { // EnterCriticalSection synchronizes code with other threads. EnterCriticalSection(&CriticalSection); // Perform a task that may cause an exception. lpBuffer = (LPTSTR) LocalAlloc(LPTR, 10); strcpy(lpBuffer,"Hello"); // possible access violation printf("%s\n",lpBuffer); LocalFree(lpBuffer); } // LeaveCriticalSection is called even if an exception occurred. __finally { LeaveCriticalSection(&CriticalSection); }