Error handling for new

This tip submitted by Upesh Jindal on 2005-12-28 06:05:13. It has been viewed 22697 times.
Rating of 5.4 with 155 votes



Using new to allocate memory may fail sometimes because of unavailability of memory on the system. To handle the situation there are two methods:
- Exception handling
- no throw method

Exception Handling: new throws exception of type bad_alloc if memory cannot be allocated. So catch this exception. e.g.
    try {
     int* p = new int [1000000000000000];
    } catch (bad_alloc b) {
      // Error Messages
    }

No throw method is another approach. Use (nothrow) in the call and then check for null-ness of the pointer. E.g. 
     int* p = new (nothrow) int [10000000000000000];
     if ( 0 == p ) {
      // Error message
     } else {
      // Normal execution
     }




More tips

Help your fellow programmers! Add a tip!