Why doesn’t new in C++ return NULL on failure

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 <new> 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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)