std::getline throwing when it hits eof

You activate the exception handling of your stream at the very beginning of your code:

stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);

Now if the extraction of formatted data such as floating-point values, integers or strings will fail, it will set the failbit:

eofbit    indicates that an input operation reached the end of an 
          input sequence;
failbit   indicates that an input operation failed to read the expected 
          characters, or that an output operation failed to generate the 
          desired characters.

While getline(stream,buffer) will indeed set the eofbit if it reaches the end of a file, it will also set the failbit, since the desired characters (a line) couldn't be extracted.

Either wrap another try-catch-block around your loop or disable the failbit exception.

Example:

#include <iostream>
#include <fstream>

int main(){
  std::ifstream stream("so.cc");
  stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);
  std::string str;

  try{
    while(std::getline(stream, str));
  }catch(std::ifstream::failure e){
    std::cerr << "Exception happened: " << e.what() << "\n"
      << "Error bits are: "
      << "\nfailbit: " << stream.fail() 
      << "\neofbit: " << stream.eof()
      << "\nbadbit: " << stream.bad() << std::endl;    
  }
  return 0;
}

Result:

Exception happened: basic_ios::clear
Error bits are:
failbit: 1
eofbit: 1
badbit: 0

Note that both eofbit and failbit are set.

See also:

  • std::ios_base::iostate
  • Table 124 in § 27.5.3.1.5 (see above)