2
votes

I have this code and just wondered why it's not throwing an exception (or in which case it should do).

From cplusplus.com :

If the function fails to open a file, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).

#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;
 }
3

3 Answers

3
votes

You did not follow the rabbit trail all of the way down
You need to tell it you want exceptions by using std::ios::exceptions. Without doing this, it indicates failure through the failbit state flag.

// 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;
}
0
votes

You would need to register the failbit flag using std::ios::exceptions() for it to throw, which you haven't done.

0
votes

I dont think fstream throws an exception on failure to open file. you have to check that with bool fstream::is_open().