如何将消息附加到std :: exception?

时间:2014-05-22 13:26:11

标签: 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;
}

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

2 个答案:

答案 0 :(得分:4)

您可以使用扩充消息抛出新异常:

throw std::ios_base::failure(exception.what() + location,
                             exception.code());

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

第二次修改:请注意,如果您捕获的异常来自std::ios_base::failure的子类,则会使用我的建议丢失部分内容。

答案 1 :(得分:2)

我认为你只能将what()转换为字符串,追加并重新抛出异常。

catch (std::ios_base::failure& exception)
{
    std::string location = std::string(" in file\n") + fileName;
    std::string error(exception.what());
    throw std::ios_base::failure(error+location);
    // throw std::ios_base::failure(error+location, exception.code()); // in case of c++11
}

请记住,因为c ++ 11失败得到了第二个参数。你也想要传递它。