簡體   English   中英

如何捕獲I / O異常(確切的I / O,而不是std :: exception)

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

我從這里嘗試了示例程序(使用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版本“x86_64-6.2.0-posix-sjlj-rt_v5-rev1”,即GCC版本6.2

這可能是一個MingW錯誤。 我使用MacOS Clang 802.0.42獲得了預期的結果。 預期的產出是:

異常打開/讀取/關閉文件

這可能是一個已知的回歸: https//gcc.gnu.org/bugzilla/show_bug.cgi?id = 66145

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM