Catching all unhandled C++ exceptions?

前端 未结 8 2133
深忆病人
深忆病人 2020-12-13 19:22

Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?

I\'m not really concerned about all the normal

相关标签:
8条回答
  • 2020-12-13 19:56

    Provided that C++11 is available, this approach may be used (see example from: http://en.cppreference.com/w/cpp/error/rethrow_exception):

    #include <iostream>
    #include <exception>
    
    void onterminate() {
      try {
        auto unknown = std::current_exception();
        if (unknown) {
          std::rethrow_exception(unknown);
        } else {
          std::cerr << "normal termination" << std::endl;
        }
      } catch (const std::exception& e) { // for proper `std::` exceptions
        std::cerr << "unexpected exception: " << e.what() << std::endl;
      } catch (...) { // last resort for things like `throw 1;`
        std::cerr << "unknown exception" << std::endl;
      }
    }
    
    int main () {
      std::set_terminate(onterminate); // set custom terminate handler
      // code which may throw...
      return 0;
    }
    

    This approach also allows you to customize console output for unhandled exceptions: to have something like this

    unexpected exception: wrong input parameters
    Aborted
    

    instead of this:

    terminate called after throwing an instance of 'std::logic_error'
      what():  wrong input parameters
    Aborted
    
    0 讨论(0)
  • 2020-12-13 19:57

    Check out std::set_terminate()

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