12.5 Throwing Exceptions from Your Own Functions

It is possible to use the Microsoft Foundation Class Library exception-handling paradigm simply to catch exceptions thrown by functions in the Microsoft Foundation Class Library or other libraries. In addition to simply catching exceptions thrown by library code, you can throw exceptions from your own code if you are writing functions that can encounter exceptional conditions.

·To throw an exception:

Use one of the Foundation Class Library helper functions, such as AfxThrowMemoryException, listed in AFX.H. These functions throw a preallocated exception object of the appropriate type.

When an exception is thrown, execution of the current function is aborted and jumps directly to the CATCH block of the innermost exception frame. The exception mechanism bypasses the normal exit path from a function. Therefore, you must be sure to delete those memory blocks that would be deleted in a normal exit. In the following example, a function tries to allocate two memory blocks and throws an exception if either allocation fails:

{

char* p1 = malloc( SIZE_FIRST );

if( p1 == NULL )

AfxThrowMemoryException();

char* p2 = malloc( SIZE_SECOND );

if( p2 == NULL )

{

free( p1 );

AfxThrowMemoryException();

}

// ... do something with allocated blocks ...

// in normal exit, both blocks are deleted

free( p1 );

free( p2 );

}

If the first allocation fails, you can simply throw the memory exception. If the first allocation is successful but the second one fails, you must free the first allocation block before throwing the exception. If both allocations succeed, then you can proceed normally and free the blocks when exiting the function.