How to throw std::exceptions with variable messages?

前端 未结 8 2092
梦如初夏
梦如初夏 2020-12-04 08:00

This is an example of what I often do when I want to add some information to an exception:

std::stringstream errMsg;
errMsg << \"Could not load config          


        
8条回答
  •  感情败类
    2020-12-04 08:51

    The standard exceptions can be constructed from a std::string:

    #include 
    
    char const * configfile = "hardcode.cfg";
    std::string const anotherfile = get_file();
    
    throw std::runtime_error(std::string("Failed: ") + configfile);
    throw std::runtime_error("Error: " + anotherfile);
    

    Note that the base class std::exception can not be constructed thus; you have to use one of the concrete, derived classes.

提交回复
热议问题