c++ - 如何使用可变消息抛出 std::exceptions?

标签 c++ exception exception-handling

这是我想在异常中添加一些信息时经常做的一个例子:

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/

相关文章:

c++ - 用sscanf使用指向float[3]的指针,得到异常

c++ - OpenGL 中的故障面部变形目标动画 (C++)

c++ - 从另一个系统访问命名管道时拒绝访问

java - 如何在 Jackson 编码(marshal)期间在 Apache Camel 路由中捕获 JsonParseException?

java - 区分相同序列化对象的最简洁方法是什么?

python - 在 Django 的自定义管理器中捕获 DoesNotExist 异常

Python 忽略异常并回到原来的位置

c++ - 将对象指针转换为 char 数组

c# - 没有参数名称的 ArgumentNullException 消息

javascript - `throw new Error` 和 `throw someObject` 有什么区别?