Today, an unexpected crash occurred while running the program. The system prompts that the STD: bad_alloc exception occurred. After searching, it is found that the exception is due to the use of new to allocate memory space, this exception is thrown when the memory space is insufficient.
Handle the exception. Use the try-catch module function to place the memory allocation statement in try. When an exception occurs, it is immediately obtained and transferred to the matched Catch Block for processing. The catch parameter is of the exception type. Here it is STD: bad_alloc.
1 int * A; 2 try 3 {4 // allocate memory 5 A = new int [bigbignum]; 6} 7 catch (STD: bad_alloc) 8 {9 // Exception Handling 10 // pop-up prompt dialog box 11 // return 12}
Note that when a large memory block is allocated, the system will handle exceptions that fail to be allocated. Avoid program running errors or crashes.