tags:

views:

71

answers:

2
+2  A: 

The iostreams by default do not throw exceptions when errors occur. If you want to enable them:

cout.execeptions( std::ios::badbit );

would enable exceptions if badbit is set.

To enable them all:

cout.execeptions( std::ios::badbit 
                   | std::ios::eofbit 
                   | std::ios::failbit );

The exceptions thrown are of type:

std::ios_base::failure

which is derived from std::exception.

In general though, it is easier not to use execptions, but to use constructs like:

while( std::getline( myStreamObj, line ) ) {
   // process line
}
anon
Thanks for your reply! I didn't know about this condition so it comes useful. Can I ask you one more small detail. Why exceptions are not a good choice here?
Abruzzo Forte e Gentile
@Abruzzo Lots of reasons - slower, don't easily support resumption, need to write more code to handle the errors. And most people reading your code will expect exceptions *not* to be used in this area, so they will find the code harder to understand.
anon
+1  A: 

If you want to capture the errors via exceptions you need to set it using ios::exception. Otherwise an exception will not be thrown. You can check out the documentation here: http://www.cplusplus.com/reference/iostream/ios/exceptions/.

You can also explicitly call ios::fail(), ios::bad() or ios::eof(). Docs here: http://www.cplusplus.com/reference/iostream/ios/

jcmoney