title: Try-Catch Block For C++ File-IO Errors Not Working
body: <p>I'm very new to the world of C++ error handling, but I was told here:<br>
  <a href="https://stackoverflow.com/questions/3622030/checking-for-file-existence-in-c">Checking for file existence in C++</a></p>
  
  <p>...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:<br>
  <a href="http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/Readafileintrycatchblock.htm" rel="nofollow noreferrer"><a href="http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/Readafileintrycatchblock.htm" rel="nofollow noreferrer">http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/Readafileintrycatchblock.htm</a></a></p>
  
  <pre><code>#include &lt;fstream&gt;
  #include &lt;iostream&gt;
  using namespace std;
  
  int main () 
  {
    try{
        char buffer[256];
        ifstream myfile ("test.txt");
  
        while (! myfile.eof() )
        {
          myfile.getline (buffer,100);
          cout &lt;&lt; buffer &lt;&lt; endl;
        }
    }catch(...){
       cout &lt;&lt; "There was an error !\n";
    }
    return 0;
  }
  </code></pre>
  
  <p>...but when I compile it using</p>
  
  <pre><code>g++ -Wall -pedantic -o test_prog main.cc
  </code></pre>
  
  <p>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?</p>
  
  <p>Also is <em>this</em> 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)?</p>
  
  <p>Thanks!</p>