error handling for new operator?

Started by
4 comments, last by blizzard999 18 years, 8 months ago
Hi I am working on a bitpacker for my library and need to allocate some buffers here and there but i wonder how i should react on a failure of "NEW" i could throw a bad alloc exception but is it worth it at all? in most cases the program will crash anyways when it runs out of memory any suggestions?
http://www.8ung.at/basiror/theironcross.html
Advertisement
Is your library intended to be used from both C or C++? Is it a source code library? Dynamically bound? What do you use internally for memory allocation? These are all factors in determining an error signalling mechanism for a library.
Quote:Original post by Basiror
Hi I am working on a bitpacker for my library and need to allocate some buffers here and there but i wonder how i should react on a failure of "NEW"
i could throw a bad alloc exception but is it worth it at all?

Given that the standard failure of new is to throw bad_alloc, probably not.

Personally, I only take the time to care about new failing in very specific circumstances... stuff like logging, that needs to work while the application is crashing down around it. Also, with STL and a good object management system, it's pretty rare to actually call new directly.
its a source code library actually most of the code is in header files just like the STL

I use the standard new operators

i usually don t care about the result of the allocation either, since i am not working on industry projects
http://www.8ung.at/basiror/theironcross.html
In that case you might as well just rely on the fact that new throws std::bad_alloc. Just make sure your code is exception safe, and let your client deal with the exception.
If a critical error happened in a constructor the best solution is throwing an exception (because the ctor does not have a return value ); however if the new does not allocate the memory requested ( and the amount is reasonable ) I think that throwing an exception is the right thing also in this case.
As you know you can throw and catch everything: simply when catch a 'new' failure terminate the application faster as you can ( and do not throw anything else in the destructors the 'rewinding' traverse ! )(that is: never throw an exception from a dtor...)

This topic is closed to new replies.

Advertisement