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.
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.
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 .
3. If no exception occurs in try block then the catch blocks are completely ignored.
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 assert
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With