这是我想在异常中添加一些信息时经常做的一个例子:
std::stringstream errMsg;
errMsg << "Could not load config file '" << configfile << "'";
throw std::exception(errMsg.str().c_str());
有更好的方法吗?
最佳答案
标准异常可以从 std::string
:
#include <stdexcept>
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);
请注意,std::exception
基类不能这样构造;您必须使用具体的派生类之一。
关于c++ - 如何使用可变消息抛出 std::exceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12261915/