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:

badbit

An unrecoverable error occurred. For example, an exception was thrown from a formatting facet, an I/O system call failed unexpectedly, and so on.

eofbit

An end-of-file upon input.

failbit

An I/O operation failed ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.