Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-Catch Block For C++ File-IO Errors Not Working

I'm very new to the world of C++ error handling, but I was told here:
Checking for file existence in C++

...that the best way to checks for file existence was with a try-catch block. From my limited knowledge on the topic, this sounds like sound advice. I located this snippet of code:
http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/Readafileintrycatchblock.htm

#include <fstream>
#include <iostream>
using namespace std;

int main () 
{
  try{
      char buffer[256];
      ifstream myfile ("test.txt");

      while (! myfile.eof() )
      {
        myfile.getline (buffer,100);
        cout << buffer << endl;
      }
  }catch(...){
     cout << "There was an error !\n";
  }
  return 0;
}

...but when I compile it using

g++ -Wall -pedantic -o test_prog main.cc

And run the program in a directory where test.txt does not exist, the prog keeps spitting out empty lines to the terminal. Can anyone figure out why?

Also is this a good way to check for file existence for a file you actually want to open and read from (versus just something where your indexing a bunch of files and checking them over)?

Thanks!

like image 657
Jason R. Mick Avatar asked Sep 02 '10 16:09

Jason R. Mick


People also ask

Which errors Cannot be handled by catch block?

As is documented, try/catch blocks can't handle StackOverflowException and OutOfMemoryException.

Is there a try except in C?

The try-except statement is a Microsoft extension to the C language that enables applications to gain control of a program when events that normally terminate execution occur. Such events are called exceptions, and the mechanism that deals with exceptions is called structured exception handling.


2 Answers

In C++ iostreams do not throw exeptions by default. What you need is

ifstream myfile("test.txt");

if(myfile) {
   // We have one
}
else {
   // we dont
}
like image 160
Artyom Avatar answered Sep 19 '22 13:09

Artyom


By default the fstream objects do not throw. You need to use void exceptions ( iostate except ); to set the exception behavior. You can fetch the current settings using iostate exceptions ( ) const;. Change your code just a bit:

#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace std;

int main () 
{
  try{
      char buffer[256];
      ifstream myfile ("test.txt");
      myfile.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
      while (myfile)
      {
        myfile.getline (buffer,100);
        cout << buffer << endl;
      }
      myfile.close();

  }catch(std::exception const& e){
     cout << "There was an error: " << e.what() << endl;
  }
  return 0;
}
like image 26
dirkgently Avatar answered Sep 22 '22 13:09

dirkgently