Posts : 826 Join date : 2011-10-11 Age : 45 Location : Balaju, Kathmandu
Subject: Error handling for new in C programming Sat Oct 22, 2011 3:37 am
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