Why doesn\'t new
return NULL
on failure? Why does it throw an exception only on failure?
As it returns a pointer to the object on successes
Before exceptions were introduced in C++:
A failing new
-expression produced a nullpointer.
In a failing constructor one assigned a nullpointer to this
.
After exceptions were introduced:
A failing ordinary new
-expression throws an exception.
In a failing constructor one throws an exception.
One difference is that failure reporting for constructors now works also for creation of objects without dynamic allocation.
Another difference is that code using new
-expressions now can be simpler since the error handling can be moved out of each such code place, and centralized.
The old nullpointer-result behavior is still available via std::nothrow
(include the
header). This implies checking at each place using new
. Thus nullpointer results are in conflict with the DRY principle, don't repeat yourself (the redundancy offers an endless stream of opportunities to introduce errors).