简体   繁体   中英

c++ uncaught exceptions on osX

I have a problem with a c++ library that I develop: I defined my own exception class (that basically only contains a string to return for the what() call) and when an exception is not caught, the goal is that the operating system would print the message from what() and terminate. This works well on Linux but on osX, the exception message is not shown (ie it directly terminates without printing anything).

So, am I correctly assuming that uncaught exceptions would lead to what() followed by a termination? What should I do on osX so the message would be shown? (knowing that I don't like the idea of setting an exception handler, since this imposes the user of the library to do it)

Thanks! Mathias

On all OS's: catch the exception in main() and print out whatever message is appropriate. If you don't catch it, it is unspecified whether destructors are run on the way out. Do you really want that?

So, am I correctly assuming that uncaught exceptions would lead to what() followed by a termination?

No. The standards don't require uncaught exceptions to print out what() . In fact, they make it pretty hard (but not impossible) to write a conforming implementation that always does so.

There's really no good way to do exactly what you want to do (print out the what() , only if the implementation isn't going to do so in this case, then carry on to terminate() as if the exception had never been caught). But that probably isn't what you really want.

This is probably what you want:

#import <exception>
#import <iostream>

int real_main(int argc, char *argv[]);

int main(int argc, char *argv[]) {
  try {
    return real_main(argc, argv);
  } catch (std::exception &e) {
    std::cerr << "exception: e.what()" << "\n";
    exit(1);
  } catch (...) {
    std::cerr << "exception not derived from std::exception\n";
    exit(1);
  }
}

int real_main(int argc, char *argv[])
{
    // real main code goes here
}

If you really want to, say, _exit or abort (or even terminate ) instead of exit ing, you can do that of course. But if you don't know, you probably want exit .

Meanwhile:

… knowing that I don't like the idea of setting an exception handler, since this imposes the user of the library to do it

You're writing a library? And you want your library to be able to terminate the process behind the application's back?

That's probably a very bad idea.

But if you really do want to do it, the same code above will work, you just have to wrap it around the entry points to your library instead of around main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM