How to throw std::exceptions with variable messages?

前端 未结 8 2093
梦如初夏
梦如初夏 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:35

    Use string literal operator if C++14 (operator ""s)

    using namespace std::string_literals;
    
    throw std::exception("Could not load config file '"s + configfile + "'"s);
    

    or define your own if in C++11. For instance

    std::string operator ""_s(const char * str, std::size_t len) {
        return std::string(str, str + len);
    }
    

    Your throw statement will then look like this

    throw std::exception("Could not load config file '"_s + configfile + "'"_s);
    

    which looks nice and clean.

提交回复
热议问题