【发布时间】: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