Difference: std::runtime_error vs std::exception()

后端 未结 2 823
执念已碎
执念已碎 2020-12-07 08:11

What is the difference between std::runtime_error and std::exception? What is the appropriate use for each? Why are they different in the first pla

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 08:39

    std::exception should be considered (note the considered) the abstract base of the standard exception hierarchy. This is because there is no mechanism to pass in a specific message (to do this you must derive and specialize what()). There is nothing to stop you from using std::exception and for simple applications it may be all you need.

    std::runtime_error on the other hand has valid constructors that accept a string as a message. When what() is called a const char pointer is returned that points at a C string that has the same string as was passed into the constructor.

    try
    {
        if (badThingHappened)
        {
             throw std::runtime_error("Something Bad happened here");
        }
    }
    catch(std::exception const& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
    } 
    

提交回复
热议问题