Correct way to inherit from std::exception

后端 未结 5 1988
猫巷女王i
猫巷女王i 2020-12-04 16:04

I\'ve just created exception hierarchy and wanted to pass char* to constructor of one of my derived classes with a message telling what\'s wrong, but apparently

5条回答
  •  时光取名叫无心
    2020-12-04 17:05

    If your goal is to create an exception so that you do not throw a generic exception (cpp:S112) you may just want to expose the exception you inherit from (C++11) with a using declaration.

    Here is a minimal example for that:

    #include 
    #include 
    
    struct myException : std::exception
    {
        using std::exception::exception;
    };
    
    int main(int, char*[])
    {
        try
        {
            throw myException{ "Something Happened" };
        }
        catch (myException &e)
        {
            std::cout << e.what() << std::endl;
        }
        return{ 0 };
    }
    

    As Kilian points out in the comment section the example depends on a specific implementation of std::exception that offers more constructors than are mentioned here.

    In order to avoid that you can use any of the convenience classes predefined in the header . See these "Exception categories" for inspiration.

提交回复
热议问题