C++ Exceptions

LayGO C++ Wrapper classes require a compiler which supports C++ runtime exception handling. In some cases, this is an optional feature which must be enabled by using a compiler option. (For instance, the Microsoft Visual C++ compiler supports exception handling, but it must be enabled via the /GX command-line option.) C++ exception handling is required for 2 reasons:

Some C++ compilers may support use of the xalloc or bad_alloc exception class for out of memory conditions. Where this is not the case, the application should be able to force this type of behavior by defining a handler function and using _set_new_handler() as shown in the following example:

#include <new.h>

class CNewException
{
    public:
        CNewException() : size(0) {};
        ~CNewException() {};
        size_t  size;
};

static CNewException newException;

static
int
newExceptionHandler
    (
    size_t  size
    )
{
    newException.size = size;

    throw &newException;
    return (0);
}

int
main
    (
    int     argc,
    char ** argv
    )
{

    _set_new_handler(newExceptionHandler);

    try
    {
        ...
    }
    catch (CNewException * exception)
    {
        // Memory allocation failed
		cerr << "Out of memory: cannot allocate "
             << exception->size
             << " bytes"
             << endl;
        ...
    }

    return (0);
}

In this example, if operator new is unable to allocate the requested memory, it will call the user supplied function, newExceptionHandler(). The function then throws an exception of type CNewException *. (Since this is the address of a statically declared CNewException, memory allocation is not required and the handler will not call itself recursively.) If an exception occurs inside the try block, the stack will be unwound and execution will resume inside the catch block.