c++memory-managementbad-alloc

How to deal with bad_alloc in C++?


There is a method called foo that sometimes returns the following error:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Abort

Is there a way that I can use a try-catch block to stop this error from terminating my program (all I want to do is return -1)?

If so, what is the syntax for it?

How else can I deal with bad_alloc in C++?


Solution

  • You can catch it like any other exception:

    try {
      foo();
    }
    catch (const std::bad_alloc&) {
      return -1;
    }
    

    Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.