Handling failed allocations
If the new operator cannot allocate the memory for an object, it will throw the std::bad_alloc exception and the pointer returned will be nullptr. Exceptions are covered in Chapter 7, Diagnostics and Debugging, so only a brief outline of the syntax will be given here. It is important that you check for failure to allocate memory in production code. The following code shows how to guard the allocation so that you can catch the std::bad_alloc exception and handle it:
// VERY_BIG_NUMER is a constant defined elsewhere
int *pi;
try
{
pi = new int[VERY_BIG_NUMBER];
// other code
}
catch(const std::bad_alloc& e)
{
cout << "cannot allocate" << endl;
return;
}
// use pointer
delete [] pi;
If any code in the try block throws an exception control it is passed to the catch clause, ignoring any other code that has not been executed yet. The catch clause checks the type of the exception object and if it is the correct type (in this case an allocation fault), it creates a reference to that object and passes control to the catch block, and the scope of the exception reference is this block. In this example, the code merely prints an error, but you would use it to take action to ensure that the memory allocation failure does not affect subsequent code.