Thursday, June 26, 2008

Exceptions

Did you ever think about what happens when you use the new operator to allocate memory for a structure but allocation fails? Well, the new operator throws an exception. Except, if you specify (std::nothrow) like this:

BYTE *p = NULL;
p = new (std::nothrow) BYTE[128];

it's a good idea to initialize the pointer to NULL and you can check whether allocation succeeded with a NULL check afterwards.

Another thing: how can a constructor report any error back to the caller? Yes, the only way is to throw an exception. So in general, it's a good idea to use try-catch blocks where there are constructor calls (eg. objects instantiated with new)