Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New (std::nothrow) vs. New within a try/catch block

I did some research after learning new, unlike malloc() which I am used to, does not return NULL for failed allocations, and found there are two distinct ways of checking whether new had succeeded or not. Those two ways are:

try {     ptr = new int[1024]; } catch(std::bad_alloc& exc) {     assert(); }; 

and

ptr = new (std::nothrow) int[1024]; if(ptr == NULL)      assert(); 

I believe the two ways accomplish the same goal, (correct me if I am wrong of course!), so my question is this:

which is the better option for checking if new succeeded, based entirely on readability, maintainability, and performance, while disregarding de-facto c++ programming convention.

like image 534
Anne Quinn Avatar asked Sep 01 '11 23:09

Anne Quinn


People also ask

Why should I not wrap every block in try catch?

Exponentially because if each method branches in two different ways then every time you call another method you're squaring the previous number of potential outcomes. By the time you've called five methods you are up to 256 possible outcomes at a minimum.

Should you use try catch blocks?

Like some others have said, you want to use try-catch blocks around code that can throw an Exception AND code that you are prepared to deal with. Regarding your particular examples, File. Delete can throw a number of exceptions, for example, IOException , UnauthorizedAccessException .

What happens if try catch block is not used?

3. If no exception occurs in try block then the catch blocks are completely ignored.


1 Answers

Consider what you are doing. You're allocating memory. And if for some reason memory allocation cannot work, you assert. Which is more or less exactly what will happen if you just let the std::bad_alloc propagate back to main. In a release build, where assert is a no-op, your program will crash when it tries to access the memory. So it's the same as letting the exception bubble up: halting the app.

So ask yourself a question: Do you really need to care what happens if you run out of memory? If all you're doing is asserting, then the exception method is better, because it doesn't clutter your code with random asserts. You just let the exception fall back to main.

If you do in fact have a special codepath in the event that you cannot allocate memory (that is, you can actually continue to function), exceptions may or may not be a way to go, depending on what the codepath is. If the codepath is just a switch set by having a pointer be null, then the nothrow version will be simpler. If instead, you need to do something rather different (pull from a static buffer, or delete some stuff, or whatever), then catching std::bad_alloc is quite good.

like image 135
Nicol Bolas Avatar answered Sep 20 '22 02:09

Nicol Bolas