捕获打开异常

catch an open exception

本文关键字:异常      更新时间:2023-10-16

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

From cplusplus.com:

如果函数打开文件失败,则为流设置failbit状态标志(如果该状态标志是使用成员异常注册的,则可能抛出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;
 }

你没有沿着兔子的足迹一路下来
您需要通过使用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 filen";
  }
  return 0;
}

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

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