1

I have a function (addShape) to read ints from a file according to the id it gets. It gets the id and the stream is as parameters. for some reason I get thrown with std::ios_base::failure after reading the last line.

while (is >> id)
    addShape(id, is, false);

I thought that this is the safest way to read from a file.

This is how I initialize the stream:

fstream is;
int id = 0;
string filename;
char answer = NULL;

// set exceptions
is.exceptions(fstream::failbit | fstream::badbit);

try { is.open(filename); }

catch (ifstream::failure e)
{
    clrscr();
    cout << "There was an error opening " << filename << endl;
    waitForEscape();
    is.close();

    return;
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Quaker
  • 1,483
  • 3
  • 20
  • 36
  • 1
    Can you show us how you're initializing the stream `is` and the code for `addShape`? You may have enabled exceptions on the stream object. – templatetypedef Jan 05 '14 at 21:59

1 Answers1

4

When you're creating the stream, notice that you're turning on exceptions whenever failbit is set:

// set exceptions
is.exceptions(fstream::failbit | fstream::badbit);

This means that any time a stream operation sets failbit, the stream will throw an exception.

Now, look at this code:

while (is >> id)
    addShape(id, is, false);

At some point the read is >> id will fail, either because you run out of data or because the data is malformed. When this happens with exceptions turned off, this will fail by setting failbit and having is >> id evaluate to false, stopping the loop. However, with exceptions turned on, when failbit is set in this case, it will throw an exception.

Depending on what you want to do, you can either

  • Not set exceptions for failbit, which will cause the loop to stop running when an error occurs, or
  • Set up an explicit exception handler around the while loop.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • I want to have an exception if the file couldn't be opened, is it possible to turn the exception off after the file is opened? – Quaker Jan 05 '14 at 22:05
  • 3
    @Quaker- Yes, that should be possible by calling `is.exceptions(0)`. That said, if you just want to throw an exception if a single operation fails, you might consider instead leaving exceptions off and then manually checking for a failure yourself and throwing an exception if something goes wrong. That seems like a more elegant solution. – templatetypedef Jan 05 '14 at 22:07