【问题标题】:No exception throw after open a file stream with non-exist files?打开不存在文件的文件流后没有异常抛出?
【发布时间】:2015-01-02 09:25:30
【问题描述】:

我正在尝试使用

std::ifstream inStream;
inStream.open(file_name);

如果file_name 不存在,则不会抛出异常。我怎样才能确保在这种情况下投掷?我正在使用 C++11

【问题讨论】:

  • @πάνταῥεῖ 您可能应该将其发布为答案,而不是评论。
  • 可以,但是不能显示哪个文件不存在;我只能显示对我不重要的故障位。
  • @Adam : 嗯,你的范围内已经有file_name...有什么问题?
  • @Adam :当然可以:捕获异常,然后抛出一个不同的异常,包括文件名。

标签: c++


【解决方案1】:

您可以通过在调用open()之前设置流exception mask来做到这一点

std::ifstream inStream;
inStream.exceptions(std::ifstream::failbit);
try {
    inStream.open(file_name);
}
catch (const std::exception& e) {
    std::ostringstream msg;
    msg << "Opening file '" << file_name 
        << "' failed, it either doesn't exist or is not accessible.";
    throw std::runtime_error(msg.str());
}

默认情况下,所有流失败情况都不会导致异常。

【讨论】:

  • e.what() 只能在文件不存在时返回“未指定的 iostream_category 错误”。
  • @AdamLee 那是你能得到 AFAIK 的最好方法。除了由open()设置的不存在或不可访问的文件之外,没有太多可能性。
  • 我编辑一个地方,我需要使用 const std::exception& e 而不是 const & std::exception。
  • 顺便说一句,看来我必须使用std::ostrstream而不是ostringstream,请确认。
  • @AdamLee 请看这里:stackoverflow.com/questions/2820221/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多