【问题标题】:How to catch I/O exception (exactly I/O, not std::exception)如何捕获 I/O 异常(确切地说是 I/O,而不是 std::exception)
【发布时间】:2017-11-14 15:45:58
【问题描述】:

我尝试了 here 的示例程序(使用 mingw-w64)。程序崩溃了。所以我编辑了它:

#include <iostream>     // std::cerr
#include <fstream>      // std::ifstream

int main()
{
    std::ifstream file;
    file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    try {
        file.open("not_existing.txt");
        while (!file.eof())
            file.get();
        file.close();
    }
    catch (std::ifstream::failure e) {
        std::cerr << "Exception opening/reading/closing file\n";
    }
    catch (const std::exception& e) {
        std::cerr << "should not reach this";
    }

    return 0;
}

现在它运行了,但打印了should not reach this,而我期待它打印Exception opening/reading/closing file

为什么我的预期是错误的?

编辑: 因为这似乎很重要,所以这是我的编译器的确切版本: mingw-w64 version "x86_64-6.2.0-posix-sjlj-rt_v5-rev1" ,即 GCC 版本 6.2

【问题讨论】:

  • 你可以试试while (file.good()) { 吗?
  • @xsami 同样的故事。在file.open("not_existing.txt"); 中抛出异常
  • 我会推荐char c; while(file.get(c)) {} 不要循环使用eof() stackoverflow.com/questions/5605125/…
  • @Galik 谢谢,但这只是来自cplusplus.com 的示例代码。我在完全不同的代码中有相同的行为。
  • 您应该通过引用捕获这两个异常。目前你有一个值,一个引用。

标签: c++ exception exception-handling io


【解决方案1】:

这可能是一个 MingW 错误。我使用 MacOS Clang 802.0.42 得到了预期的结果。预期的输出是:

异常打开/读取/关闭文件

这可能是一个已知的回归:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145

【讨论】:

  • @yar 您可以下载最新的 MinGW-w64(即 GCC 7.1.0)。似乎该错误已在 GCC 7.0 中修复。
  • @HolyBlackCat 是的,我会在几分钟内尝试,谢谢!
猜你喜欢
  • 2013-10-03
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 2013-01-07
相关资源
最近更新 更多