5

This is somewhat similar to "Disabling C++ exceptions, how can I make any std:: throw() immediately terminate?." I would like my program to terminate whenever an exception is thrown out of the STL.

The problem is as follows: I am writing a library which is then loaded as a shared object and executed by a program I don't have control over. Unfortunately this program runs everything in a big try bock so that I don't get a stack trace/core dump if an error is thrown, rendering the ::at class of function's out of range error useless.

This sounds like the ideal use case for -fno-exceptions, but I can't just use -fno-exceptions, because boost_log and the program that calls me both have exception handling defined in their headers giving me compile errors with -fno-exceptions.

Is there a way to enable -fno-exceptions only for stl exceptions?

Community
  • 1
  • 1
niklasfi
  • 15,245
  • 7
  • 40
  • 54
  • In libstdc++, if `at` detects an argument out of range, it calls `void std::__throw_out_of_range(char const*)`. If you define your own function with the same name and arrange for it to be picked at link time (LD_PRELOAD may be easiest for an experiment), you should be able to change the behavior to whatever you like. – Marc Glisse Apr 11 '14 at 07:12
  • The "STL" as a separate library pretty much stopped existing in 1998; there really is no such thing as "STL exceptions" in todays C++. Much of the current library can be traced back to Boost instead of the STL. (And of course, quite a few compiler vendors have reimplemented these classes) – MSalters Apr 11 '14 at 07:32
  • If you are doing C++11, you could mark your function as `noexcept`, so if an exception tries to escape it, the program will be immediately terminated. – Marc Glisse Apr 11 '14 at 07:56
  • @MarcGlisse it seems `noexcept` is really the best solution in my case. – niklasfi Apr 11 '14 at 12:38

1 Answers1

2

With C++11, the easiest way to do is to add noexcept to the signature of the top level function that is called from your shared library:

void called_func() noexcept;

This will cause any unhandled exceptions in the called_func stack frame (or below if they are not handled) to terminate the execution of the program.

niklasfi
  • 15,245
  • 7
  • 40
  • 54