Using a Termination Handler

The following example shows how a try-finally statement 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 try-finally statement guarantees that this will happen.

For more information about critical section objects, see Synchronization.

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);

}