By default a stream does not throw any exceptions. You must explicitly activate an exception because a stream contains an exception mask. Each flag in this mask corresponds to one of the error flags. For example, once the badbit flag is set in the exception mask, an exception is thrown each time the badbit flag is set in the stream state.
NOTE -- An example of using an exception mask is provided by the streams layer, which catches bad_alloc exceptions thrown during allocation of its internal resources, iword and pword. It then setsbadbit or failbit. An exception would be thrown only if the corresponding bit in the exception mask is set. The exception thrown isios_base::failure.
The following code demonstrates how to activate an exception on an input stream object in:
extern std::istream& in;
try {
in.exceptions(std::ios_base::badbit |
std::ios_base::failbit); //1
in >> x;
// do lots of other stream i/o
}
catch(std::ios_base::failure& exc) { //2
std::cerr << exc.what() << std::endl;
throw;
}
Generally, it is a good idea to activate the badbit exception and suppress the eofbit and failbit exceptions, because the latter do not represent exceptional states. A badbit situation, however, is likely to be a serious error condition similar to the memory shortage indicated by a bad_alloc exception. Unless you want to suppress exceptions thrown by iostreams altogether, we would recommend that you switch on the badbit exception and turn off eofbit and failbit.