Errors and Exceptions
By default, I/O streams do not raise exceptions for
errors. Instead, each stream keeps a mask of error bits called the
I/O state. The state mask keeps track of formatting
failures, end-of-file conditions, and miscellaneous error conditions.
The ios_base class template defines
several member functions for testing and modifying the state flags
(rdstate, setstate, fail, etc.).
A common idiom is to read from an input stream until an input
operation fails. Because this idiom is so common, the standard library
makes it easy. Instead of calling rdstate and testing the state explicitly, you
can simply treat the stream object as a Boolean value: true means the state is good, and false means the state has an error condition.
Most I/O functions return the stream object, which makes the test even
easier:
while (cin.get(c)) cout.put(c);
The basic_ios class overloads
operator void* to return a non-null pointer if the
state is good or a null pointer for any error condition. Similarly, it
overloads operator! to return
true for any error condition. (As
explained later in this section, an end-of-file is not an error
condition.) This latter test is often used in conditional
statements:
if (! cout)
throw("write error");The state mask has three different error bits:
badbitAn unrecoverable error occurred. For example, an exception was thrown from a formatting facet, an I/O system call failed unexpectedly, and so on.
eofbitAn end-of-file upon input.
failbitAn I/O operation failed ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access