Apache C++ Standard Library User's Guide

## 29.3 Catching Exceptions

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 sets `badbit` or `failbit`. An exception would be thrown only if the corresponding bit in the exception mask is set. The exception thrown is `ios_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;
    }

`//1` | In calling the `exceptions()` function, you indicate what flags in the stream's state shall cause an exception to be thrown. [Each change of either the stream state or the exception mask can result in an exception being thrown. This is because the functions `setstate()` and `exception()` raise an exception in case the exception mask requires it.]
`//2` | Objects thrown by the stream's operations are of types derived from `std::ios_base::failure`. Hence this catch clause catches all stream exceptions in principle. We qualify this generalization because a stream might fail to catch certain exceptions like `std::bad_alloc`, for example, so that exceptions other than `std::ios_base::failure` might be raised. That's how exception handling in C++ works: you never know what exceptions will be raised.

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`.