Handle the Exception Locally

The TRY/CATCH paradigm provides a good way to avoid memory leaks by programming defensively to ensure that your objects are destroyed when exceptions occur. For example, the previous example could be rewritten as shown below:

void SomeFunc()

{

CPerson* myPerson = new CPerson;

TRY

{

// do something that might throw an exception

myPerson->SomeFunc();

}

CATCH( CException, e )

{

// handle the exception locally

}

END_CATCH

// now destroy the object before exiting

delete myPerson;

}

This new example sets up an exception handler to catch the exception and handle it locally. It then exits the function normally and destroys the object. The important aspect of this example is that a context to catch the exception is established with the TRY/CATCH blocks. Without a local exception frame, the function would never know that an exception had been thrown and would not have the chance to exit normally and destroy the object.