How to throw std::exceptions with variable messages?

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

    Maybe this?

    throw std::runtime_error(
        (std::ostringstream()
            << "Could not load config file '"
            << configfile
            << "'"
        ).str()
    );
    

    It creates a temporary ostringstream, calls the << operators as necessary and then you wrap that in round brackets and call the .str() function on the evaluated result (which is an ostringstream) to pass a temporary std::string to the constructor of runtime_error.

    Note: the ostringstream and the string are r-value temporaries and so go out of scope after this line ends. Your exception object's constructor MUST take the input string using either copy or (better) move semantics.

    Additional: I don't necessarily consider this approach "best practice", but it does work and can be used at a pinch. One of the biggest issues is that this method requires heap allocations and so the operator << can throw. You probably don't want that happening; however, if your get into that state your probably have way more issues to worry about!

提交回复
热议问题