Can the new
operator throw an exception in real life?
And if so, do I have any options for handling such an exception apart from killing my application?
In Unix systems, it's customary to run long-running processes with memory limits (using ulimit
) so that it doesn't eat up all of a system's memory. If your program hits that limit, you will get std::bad_alloc
.
Update for OP's edit: the most typical case of programs recovering from an out-of-memory condition is in garbage-collected systems, which then performs a GC and continues. Though, this sort of on-demand GC is really for last-ditch efforts only; usually, good programs try to GC periodically to reduce stress on the collector.
It's less usual for non-GC programs to recover from out-of-memory issues, but for Internet-facing servers, one way to recover is to simply reject the request that's causing the memory to run out with a "temporary" error. ("First in, first served" strategy.)