HANDLING MEMORY ALLOCATION ERRORS

When you used the new operator to allocate memory (as you saw in Chapters 4 and 5), you ignored the possibility that the memory might not be allocated. If the memory isn’t allocated, an exception is thrown that results in the termination of the program. Ignoring this exception is quite acceptable in most situations because having no memory left is usually a terminal condition for a program that you can usually do nothing about. However, there can be circumstances where you might be able to do something about it if you had the chance, or you might want to report the problem in your own way. In this situation, you can catch the exception that the new operator throws. Let’s contrive an example to show this happening.

TRY IT OUT: Catching an Exception Thrown by the new Operator
The exception that the new operator throws when memory cannot be allocated is of type bad_alloc. bad_alloc is a class type defined in the new standard header file, so you’ll need an #include directive for that. Here’s the code:
// Ex6_06.cpp // Catching an exception thrown by new #include<new> // For bad_alloc type #include<iostream> using std::bad_alloc; using std::cout; using std::endl; int main( ) { char* pdata(nullptr); size_t count(~static_cast<size_t>(0)/2); try { pdata = new char[count]; cout << "Memory allocated." << endl; } catch(bad_alloc &ex) { cout << "Memory allocation failed." << endl << "The information from the exception object is: " << ex.what() << endl; ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.