How to throw std::exceptions with variable messages?

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

    There are different exceptions such as runtime_error, range_error, overflow_error, logic_error, etc.. You need to pass the string into its constructor, and you can concatenate whatever you want to your message. That's just a string operation.

    std::string errorMessage = std::string("Error: on file ")+fileName;
    throw std::runtime_error(errorMessage);
    

    You can also use boost::format like this:

    throw std::runtime_error(boost::format("Error processing file %1") % fileName);
    

提交回复
热议问题