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

前端之家收集整理的这篇文章主要介绍了c – 如何捕获I / O异常(确切的I / O,而不是std :: exception)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试了 here的示例程序(使用mingw-w64).该计划崩溃了.所以我编辑了它:
  1. #include <iostream> // std::cerr
  2. #include <fstream> // std::ifstream
  3.  
  4. int main()
  5. {
  6. std::ifstream file;
  7. file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  8. try {
  9. file.open("not_existing.txt");
  10. while (!file.eof())
  11. file.get();
  12. file.close();
  13. }
  14. catch (std::ifstream::failure e) {
  15. std::cerr << "Exception opening/reading/closing file\n";
  16. }
  17. catch (const std::exception& e) {
  18. std::cerr << "should not reach this";
  19. }
  20.  
  21. return 0;
  22. }

现在它运行,但打印不应该达到这个,而我期望它打印异常打开/读取/关闭文件.

为什么我的期望错了?

编辑:
因为这似乎是一个重点,这里是我的编译器的确切版本:mingw-w64版本“x86_64-6.2.0-posix-sjlj-rt_v5-rev1”,即GCC版本6.2

解决方法

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

Exception opening/reading/closing file

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

猜你在找的C&C++相关文章