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?
It depends on the compiler/runtime and on the operator new
that you are using (e.g. certain versions of Visual Studio will not throw out of the box, but would rather return a NULL
pointer a la malloc
instead.)
You can always catch
a std::bad_alloc
exception, or explicitly use nothrow new to return NULL
instead of throwing. (Also see past StackOverflow posts revolving around the subject.)
Note that operator new
, like malloc
, will fail when you have run out of memory, out of address space (e.g. 2-3GB in a 32-bit process depending on the OS), out of quota (ulimit
was already mentioned) or out of contiguous address space (e.g. fragmented heap.)