Throw Exceptions After Destroying Objects

Another way to handle exceptions is to pass them on to the next outermost exception-handling context. In your CATCH block, you can do some cleanup of your locally allocated objects and then throw the exception on for further processing. The following code shows how this can be done:

void SomeFunc()

{

CPerson* myPerson = new CPerson;

TRY

{

// do something that might throw an exception

myPerson->SomeFunc();

}

CATCH( CException, e )

{

// destroy the object before passing exception on

delete myPerson;

// throw the exception to the next handler

THROW_LAST( );

}

END_CATCH

// on normal exits, destroy the object

delete myPerson;

}

If you call functions that can throw exceptions, you can use TRY/CATCH blocks to make sure that you catch the exceptions and have a chance to destroy any objects you have created. In particular, be aware that many Microsoft Foundation Class Library functions can throw exceptions.