- cout is an instance of type "ostream"
ostream::operator<< says that
If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
This indicates to me that cout can throw an exception. Is this true? What kind of scenario could force this?
Yes, but practically nobody ever calls
cout.exceptions(iostate)
to enable that.Edit to expound:
std::ios_base
is an abstract class that provides basic utility functions for all streams.std::ios_base<CharT, Traits>
is an abstract subclass thereof, adding more utility functions.std::ios_base::iostate
is a bitmask type, consisting of the following bits, with may beor
ed:Additionally,
iostate::goodbit
is equivalent toiostate()
(basically a 0).Normally, when you perform I/O, you check the boolean value of the stream to see if an error occurred, after every input operation, e.g.
if (cin >> val) { cout << val; }
... for output, it's okay to simply emit a bunch and only check success at the end (or for cout, to not check at all).However, some people prefer exceptions, so each individual stream can be configured to turn some of those return values into exceptions:
This is rarely done in C++, since we don't mindlessly worship exceptions like adherents of some other languages. In particular, "something went wrong with I/O" is a usual case, so it doesn't make sense to contort control flow.
An example:
(Note that, on Unix systems, you have to ignore SIGPIPE in order for the program to even have a chance to handle such errors, since for many programs, simply exiting is the right thing to do - this is generally what allows
head
to work)