Can't seem to get exceptions working with istreams

I am trying to use streams (specifically cin) to throw exceptions when eof() or fail() are true, but it does not work!! What could I be doing wrong? Does it have to do with can being "tied" to cout??

Thanks in advance,
Juan

1
2
3
4
5
6
7
8
9
10
11
12

cin.exceptions( ios_base::eofbit | ios_base::failbit );
try { 
     cout << "Enter integer: " << endl;
     int val;           
     cin >> val;  // entering a non integer (e.g. ko) should throw exception
                
}
catch(ios_base::failure& err) {
     cout << "error" << '\n';
}
Why would it throw an exception there? You signaled 'eof' and 'fail' to throw an exception. Entering a non-integer shouldn't signal either 'eof' or 'fail'.
Last edited on
Oddly, the OPs code works as intended for me, in two different compilers.

Yes, entering a non-integer when cin >> is expecting an integer does set the fail() flag.

You can experiment to see which flags are set under what circumstance like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() 
{
    istringstream ss("2 3 A 7 ");  // change the contents of the input string here
    
    int n;
    for (int i=0; i<4; i++)
    {
        ss >> n;
        cout << n << '\n';
        cout << "good() " << ss.good() << '\n';
        cout << "bad()  " << ss.bad()  << '\n';
        cout << "fail() " << ss.fail() << '\n';
        cout << "eof()  " << ss.eof()  << "\n\n";   
    }
}


Unfortunately none of this helps solve the original question. Sorry about that.
Hmm. I did not know that. Now I do. Thank you!
Sorry for giving false information.
Last edited on
Anybody knows how to make iostreams throw exceptions, say upon hitting eof or fail?


Topic archived. No new replies allowed.