【问题标题】:catch an open exception捕获一个打开的异常
【发布时间】:2014-07-25 12:01:20
【问题描述】:

我有这段代码,只是想知道为什么它没有抛出异常(或者在这种情况下应该抛出异常)。

来自cplusplus.com

如果函数无法打开文件,则会为流设置故障位状态标志(如果该状态标志是使用成员异常注册的,则可能会抛出 ios_base::failure)。

#include <fstream>
#include <exception>
#include <iostream>

int main() {
  std::ofstream fs;

  try {
    fs.open("/non-existing-root-file");
  } catch (const std::ios_base::failure& e) {
    std::cout << e.what() << std::endl;
  }

  if (fs.is_open())
   std::cout << "is open" << std::endl;
  else
   std::cout << "is not open" << std::endl;

   return 0;
 }

【问题讨论】:

    标签: c++ exception io


    【解决方案1】:

    我认为 fstream 不会在打开文件失败时引发异常。您必须使用 bool fstream::is_open() 进行检查。

    【讨论】:

      【解决方案2】:

      您需要使用std::ios::exceptions() 注册failbit 标志以使其抛出,您还没有这样做。

      【讨论】:

        【解决方案3】:

        你没有跟随兔子的踪迹all of the way down
        您需要使用std::ios::exceptions 告诉它您想要例外。如果不这样做,它会通过failbit 状态标志指示失败。

        // ios::exceptions
        #include <iostream>     // std::cerr
        #include <fstream>      // std::ifstream
        
        int main () {
          std::ifstream file;
          ///next line tells the ifstream to throw on fail
          file.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
          try {
            file.open ("test.txt");
            while (!file.eof()) file.get();
            file.close();
          }
          catch (std::ifstream::failure e) {
            std::cerr << "Exception opening/reading/closing file\n";
          }
        
          return 0;
        }
        

        【讨论】:

        • 当然,您永远不会希望failbit 触发异常,因为它也是检测文件结尾的唯一方法。
        • 我不知道你为什么需要例外。如果它对你的代码组织和流程有意义,你总是可以抛出自己的。
        • badbit 上出现异常有时很有用;仅应在出现硬件问题(磁盘错误、连接丢失等)的情况下设置。其他:failbit用于识别文件结尾,eofbit即使没有问题也可以设置。
        • 请注意实现错误:stackoverflow.com/a/20372624/560648
        猜你喜欢
        • 1970-01-01
        • 2016-12-17
        • 1970-01-01
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        • 2011-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多