C++ unhandled exceptions

后端 未结 2 1948
鱼传尺愫
鱼传尺愫 2021-02-08 16:08

Does C++ offer a way to \'show\' something visual if an unhandled exception occurs?

What I want to do is to make something like assert(unhandled exception.msg())

相关标签:
2条回答
  • 2021-02-08 16:40

    Microsoft Visual C++ allows you to hook unhandled C++ exceptions like this. This is standard STL behaviour.

    You set a handler via a call to set_terminate. It's recommended that your handler do not very much work, and then terminate the program, but I don't see why you could not signal something via an assert - though you don't have access to the exception that caused the problem.

    0 讨论(0)
  • 2021-02-08 16:58

    There's no way specified by the standard to actually display the message of the uncaught exception. However, on many platforms, it is possible anyway. On Windows, you can use SetUnhandledExceptionFilter and pull out the C++ exception information. With g++ (appropriate versions of anyway), the terminate handler can access the uncaught exception with code like:

       void terminate_handler()
       {
           try { throw; }
           catch(const std::exception& e) { log(e.what()); }
           catch(...) {}
       }
    

    and indeed g++'s default terminate handler does something similar to this. You can set the terminate handler with set_terminate.

    IN short, no there's no generic C++ way, but there are ways depending on your platform.

    0 讨论(0)
提交回复
热议问题