- 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 be or
ed:
badbit (used for weird underlying errors)
eofbit (used after you hit EOF)
failbit (the normal error for badly-formatted input)
Additionally, iostate::goodbit
is equivalent to iostate()
(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:
std::ios_base::iostate exceptions() const;
void exceptions(std::ios_base::iostate except);
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:
$ cat cout.cpp
#include <iostream>
int main()
{
std::cout.exceptions(std::cout.badbit);
std::cout << "error if written to a pipe" << std::endl;
}
$ sh -c 'trap "" PIPE; ./cout | true'
vvv 2018-06-21 23:33:13-0700
terminate called after throwing an instance of 'std::ios_base::failure[abi:cxx11]'
what(): basic_ios::clear: iostream error
Aborted
(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)