Exceptions are one of the most flamed topics in C++. But before I talk about the operator new I want to say a few things in general about them. There are many ways to use exceptions, different approaches. Although, it costs more than error checking in sake of speed, it is pretty convenient and usable. Well, some people use it to replace these return code tests. Others use it in rare cases where something less expected happens. I even saw some justified reasons to why not use it. For instance, you can’t see if a function throws an exception from merely looking at its interface. Every library has its own type of exception base class, CAtlException, std::exception, etc… And you should not let anything slip your catch clause. So sometimes it might be pretty annoying to catch them all, and then you have to multiple your inside-catch-clause-code for handling each different exception. And if you have C++, you won’t dare using goto, even not for a cleanup…Of course, there are good sides also and that’s why most people use them after all.
If we take a look at the operator new, that’s the C++ raw memory allocator, we will see that it might throw an std::bad_alloc in case of failure, which is 100% legitimate, because most of the times you just expect that it will return your a pointer to a valid contigious block of memory. But now, assuming I use my own internal exceptions type for my application; Why do I need everytime to catch this exception and rethrow the converted exception? This is waste of time both in development and in run time. And there are some approaches who believe you don’t have to catch it at all, because if it is thrown, you are dead anyways. Now tell me seriously, if you write a real software for a company, you are not going to catch it? now gimme a break! So catching it you must, and therefore I don’t think every usage of the new operator should be wrapped by its own try and catch if you wrap it anyways with catching your own application’s exception. So eventually, after lots of discussions with my colleagues, we decided it suits us mostly to overload the global operator new function with our own custom function with a single change, that it will throw our exception rather than std::bad_alloc in case of failure. Overloading that operator, requires you to overload the array interface also. Don’t forget, when overloading new you will want to overload delete… :)