Catching all unhandled C++ exceptions?

前端 未结 8 2151
深忆病人
深忆病人 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:51

    Update: This covers c++98 only.

    From More Effective C++ by Meyers (pg 76), you could define a function that gets called when a function generates an exception that is not defined by its exception specification.

    void convertUnexpected()
    {
        // You could redefine the exception here into a known exception
        // throw UnexpectedException();
    
        // ... or I suppose you could log an error and exit.
    }
    

    In your application register the function:

    std::set_unexpected( convertUnexpected );
    

    Your function convertUnexpected() will get called if a function generates an exception that is not defined by its exception specification... which means this only works if you are using exception specifications. ;(

提交回复
热议问题