如何向std::异常追加消息

  • 本文关键字:异常 消息 追加 std 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 filen") + fileName;
    // append the "location" to the error message;
    throw;
}

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

您可以抛出一个新的异常,并添加消息:

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

Edit:第二个参数exception.code()来自c++ 11.

第二次编辑:注意,如果你捕获的异常是来自std::ios_base::failure的子类,你将失去它的一部分,使用我的建议。

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

catch (std::ios_base::failure& exception)
{
    std::string location = std::string(" in filen") + 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失败获得第二个参数以来。

最新更新