3

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 Answers 3

4

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;
}
4
  • 1
    And of course, you never want to have failbit triggering an exception, since it is the only way you can detect end of file too. Jun 4, 2014 at 17:54
  • I don't know why you would even need an exception. You could always throw your own if it makes sense for your code organization and flow.
    – crashmstr
    Jun 4, 2014 at 17:56
  • It's occasionally useful to have an exception on badbit; that should only be set in case of a hardware problem (disk error, lost connection, etc.). For the others: failbit is used in the recognition of end of file, and eofbit can be set even if no problem has occurred. Jun 4, 2014 at 18:07
  • Watch out for implementation bugs, though: stackoverflow.com/a/20372624/560648 Jul 10, 2017 at 13:29
0

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.