如何向 std::exception 添加消息?

Mar*_*dik 7 c++

我想做以下事情:

std::string fileName = "file";
std::ifstream in(fileName.c_str());
in.exceptions(std::istream::failbit);

try
{
    loadDataFrom(in);
}
catch (std::ios_base::failure& exception)
{
    std::string location = std::string(" in file\n") + fileName;
    // append the "location" to the error message;
    throw;
}
Run Code Online (Sandbox Code Playgroud)

如何将错误消息附加到异常中?

lri*_*eau 5

您可以抛出一个新的异常,并带有增强的消息:

throw std::ios_base::failure(exception.what() + location,
                             exception.code());
Run Code Online (Sandbox Code Playgroud)

编辑:第二个参数exception.code()来自 C++11。

第二次编辑:请注意,如果您捕获的异常来自 的子类std::ios_base::failure,则使用我的建议,您将丢失其中的一部分。