2

In our application, we log any crashes into a log file with stack trace included. We can use these reports to identify crash causes.

The problem is, that we tend to catch std::exception on several places (a lot actually), which makes the report effectively useless when bad_alloc is thrown, as the stack trace is lost.

How to change the behaviour, so instead of throwing bad_alloc, the program aborts? As we write in 3 different operating systems, so 3 different std implementations are used, changing the std itself is something we would like to avoid.

kovarex
  • 1,766
  • 18
  • 34
  • 2
    Perhaps you should rethink your design on catching `std::exception` and instead catching more *specific* exceptions? Catching `std::exception` is almost as bad as catching `...` IMO. – Some programmer dude Jul 31 '17 at 13:03
  • Possible dup https://stackoverflow.com/questions/7277637/new-stdnothrow-vs-new-within-a-try-catch-block – stark Jul 31 '17 at 13:16

2 Answers2

7

Besides a rethink or redesign to catch more tailored exceptions (which I really recommend) you have two solutions:

  1. Use the "no-throw" variants of operator new and operator new[]. Check for a returned null pointer, and abort.

  2. Set a new handler that calls std::terminate.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

I checked the exception hierarchy (http://en.cppreference.com/w/cpp/error/exception) and it seems, that we never need to catch anything outside std::runtime_exception and all of our internal exception types are derived from std::runtime_exception.

So I just changed that the broadest catch we have in our program is std::runtime_error so std::bad_alloc is becomes exception, which we can properly manage.

Edit: This can only be used since C++11

kovarex
  • 1,766
  • 18
  • 34