C++ Programming: Throwing Exceptions

By Stephen R. Davis

A C++ function that allocates resources locally may need to catch an exception, do some processing, and then rethrow it up the stack chain. Consider the following example:

void fileFunc()
{
    ofstream* pOut = new ofstream("File.txt");
    otherFunction();
    delete pOut;
}

As many programmers know, the memory allocated by new isn′t returned to the heap automatically. If otherFunction() were to throw an exception, control would exit the program without invoking delete, and the memory allocated at the beginning of fileFunc() would be lost.

To avoid this problem, fileFunc() can include a catch(…) to catch any exception thrown:

void fileFunc()
{
    ofstream* pOut = new ofstream("File.txt");
    try
    {
      otherFunction();
      delete pOut;
    }
    catch(...)
    {
        delete pOut;
        throw;
    }
}

Within this phrase, fileFunc() returns the memory it allocated earlier to the heap. However, it is not in a position to process the remainder of the exception because it has no idea what could have gone wrong. It doesn’t even know what type of object it just caught.

The throw keyword without any arguments rethrows the current exception object back up the chain to some function that can properly process the error.