Can the C++ `new` operator ever throw an exception in real life?
Yes, new
can and will throw if allocation fails. This can happen if you run out of memory or you try to allocate a block of memory too large.
You can catch the std::bad_alloc
exception and handle it appropriately. Sometimes this makes sense, other times (read: most of the time) it doesn't. If, for example, you were trying to allocate a huge buffer but could work with less space, you could try allocating successively smaller blocks.
The new operator, and new[] operator should throw std::bad_alloc
, but this is not always the case as the behavior can be sometimes overridden.
One can use std::set_new_handler
and suddenly something entirely different can happen than throwing std::bad_alloc
. Although the standard requires that the user either make memory available, abort, or throw std::bad_alloc
. But of course this may not be the case.
Disclaimer: I am not suggesting to do this.