Policy with catching std::bad_alloc

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.


Handle the exception when you can. If an allocation fails, and your application can't continue without that bit of memory, why bother checking for the error?

Handle the error when it can be handled, when there is a meaningful way to recover. If there's nothing you can do about the error, just let it propagate.


I usually catch exceptions at the point where the user has initiated an action. For console application this means in main, for GUI applications I put handlers in places like button on-click handlers and such.

I believe that it makes little sense catching exceptions in the middle of an action, the user usually expects the operation to either succeeds or completely fail.