devxlogo

Exceptions and operator new

Exceptions and operator new

Standard C++ states that operator new should throw an exception of type std::bad_alloc when it fails. This is different from previous stages of C++ and it means two important things: 1. If your code does not contain a catch statement to handle an std::bad_alloc exception, your program will crash whenever new fails, even if that exception occurs deep down in some library routine you never knew was there.2. Testing whether the pointer returned from new == 0 is completely useless; in case of success, your test will waste system resources in vain, checking a condition which is already guaranteed to be false. (Because no exception has been thrown, the tested pointer cannot be a null pointer.). And in cases of failure, the thrown exception will abort the current thread of execution right from where it was thrown, so the next lines of code will not be executed:

 void* f(int size) {	char *p = new char [size]; 	//A COMPLETELY USELESS TEST	If (p == 0) { //we won

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist