Search code examples
c++coding-stylenew-operatortry-catch

Policy with catching std::bad_alloc


So I use Qt a lot with my development and love it. The usual design pattern with Qt objects is to allocate them using new.

Pretty much all of the examples (especially code generated by the Qt designer) do absolutely no checking for the std::bad_alloc exception. Since the objects allocated (usually widgets and such) are small this is hardly ever a problem. After all, if you fail to allocate something like 20 bytes, odds are there's not much you can do to remedy the problem.

Currently, I've adopted a policy of wrapping "large" (anything above a page or two in size) allocations in a try/catch. If that fails, I display a message to the user, pretty much anything smaller, I'll just let the app crash with a std::bad_alloc exception.

So, I wonder what the schools of thought on this are on this?

Is it good policy to check each and every new operation? Or only ones I expect to have the potential to fail?

Also, it is clearly a whole different story when dealing with an embedded environment where resources can be much more constrained. I am asking in the context of a desktop application, but would be interested in answers involving other scenarios as well.


Solution

  • The problem is not "where to catch" but "what to do when an exception is caught".

    If you want to check, instead of wrapping with try catch you'd better use

        #include <new>
        x = new (std::nothrow) X();
        if (x == NULL) {
            // allocation failed
        }
    

    My usual practice is

    • in a non-interactive program, catch at main level and display an adequate error message there.

    • in a program having a user interaction loop, catch also in the loop so that the user can close some things and try to continue.

    Exceptionally, there are other places where a catch is meaningful, but it's rare.