Thursday, 9 April 2015

Standard Exception Handling for Streams

C++  provides standard exception handling for streams. You can use the exceptions()
method to specify the flags in the status-word of a stream that will cause
exceptions to be thrown.
The exceptions() method is defined in the ios stream base class. The method
expects one or multiple state flags separated by the | sign. An exception is then thrown for the flags specified.

Example:     ifstream ifstrm("account.fle");
                        fstrm.exceptions(ios::failbit | ios::badbit);

On accessing the fstrm stream an exception is thrown if either one of the flags
ios::failbit or ios::badbit is raised. The operation that caused the error is then
terminated and the state flags are cleared by a call to clear(rdstate());.

The exception thrown here is of a standard exception class, failure. This type is
defined as a public element in the ios base class and comprises the virtual method
what() that returns a C string containing the cause of the error. The exception handler
will normally send the string to standard error output.

You can call exceptions() without any arguments to discover the state flags in a
status-word of a stream that can cause an exception to be thrown. If a bit is set in the
return value of the exceptions() method, an appropriate exception will be thrown
whenever this error occurs.

Example:   iostate except = fstrm.exceptions();
                      if( except & ios::eofbit) ...

This statement uses a bitwise AND operator to ascertain whether an exception is thrown when end-of-file is reached.

No comments:

Post a Comment