简体   繁体   English

如何捕获I / O异常(确切的I / O,而不是std :: exception)

[英]How to catch I/O exception (exactly I/O, not std::exception)

I tried the example program from here (with mingw-w64). 我从这里尝试了示例程序(使用mingw-w64)。 The program crashed. 该计划崩溃了。 So I edited it: 所以我编辑了它:

#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;
}

Now it runs, but prints should not reach this , while I was expecting it to print Exception opening/reading/closing file . 现在它运行,但打印should not reach this ,而我期望它打印Exception opening/reading/closing file

Why is my expectation wrong? 为什么我的期望错了?

EDIT: since this seems to be an important point, here's the exact version om my compiler: mingw-w64 version "x86_64-6.2.0-posix-sjlj-rt_v5-rev1" , ie GCC version 6.2 编辑:因为这似乎是一个重点,这是我的编译器的确切版本:mingw-w64版本“x86_64-6.2.0-posix-sjlj-rt_v5-rev1”,即GCC版本6.2

This may be a MingW bug. 这可能是一个MingW错误。 I get the expected result using MacOS Clang 802.0.42. 我使用MacOS Clang 802.0.42获得了预期的结果。 The expected output being: 预期的产出是:

Exception opening/reading/closing file 异常打开/读取/关闭文件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM