Figure 17.5 demonstrates new
implicitly throwing bad_alloc
on failure to allocate the requested memory. The for
statement (lines 16–20) inside the try
block should loop 50 times and, on each pass, allocate an array of 50,000,000 double
values. If new
fails and throws a bad_alloc
exception, the loop terminates, and the program continues in line 22, where the catch
handler catches and processes the exception. Lines 24–25 print the message "Exception occurred:"
followed by the message returned from the base-class-exception
version of function what
(i.e., an implementation-defined exception-specific message, such as "bad allocation"
in Microsoft Visual C++). The output shows that the program performed only four iterations of the loop before new
failed and threw the bad_alloc
exception. Your output might differ based on the physical memory, disk space available for virtual memory on your system and the compiler you’re using.