### Using Assertion Macros

The assertion macros provide a convenient mechanism for testing if a given expression is true and, if it is not true, automatically throwing an exception. When you use an assertion macro, you pass as input an expression that you anticipate to be true.

There are three assertion macros:

- IASSERT
- IASSERTSTATE
- IASSERTPARM

The IASSERT macro tests the expression you provide and, if it is false, throws the IAssertionFailure exception.

The IASSERTSTATE macro tests the expression you provide and, if it is false, invokes the IExcept__assertState function. The IExcept__assertState function creates an IInvalidRequest exception. Location information is added to the exception, which is then logged and thrown.

The IASSERTPARM macro tests the expression you provide and, if it is false, invokes the IExcept__assertParameter function. The IExcept__assertParameter function creates an IInvalidParameter exception. Location information is added to the exception, which is then logged and thrown.

Consider the following simple example of using the IASSERTSTATE macro. The getFirstChar function calls the IASSERTSTATE macro with a get call as an argument. If the get call fails, it returns zero and the IASSERTSTATE macro throws an IInvalidRequest exception.

    //   Using the IASSERTSTATE macro

    #include <iostream.h>
    #include <fstream.h>
    #include <iexcept.hpp>

    void openFile(fstream& fs, char *filename){
       fs.open(filename, ios::in);
       }
    char getFirstChar(fstream& fs) {
       char c;
       IASSERTSTATE(fs.get(c));
       return c;
       }

    void main() {
       char c;
       char * filename = "source.dat";
       fstream fs;
       openFile(fs, filename);
       try {
          c = getFirstChar(fs);
          cout << "Here is first character: " << c << endl;
       }
       catch(IException ï)
       {
          cout << "Type of exception is: " << ie.name() << endl;
          cout << "Location of exception is: "
               << ie.locationAtIndex(0)->fileName() << endl;
          if (ie.isRecoverable())
             cout << "Exception is recoverable" << endl;
          else
             cout << "Exception is unrecoverable" << endl;
       }
    }

Suppose that this example is run, and the source.dat file is not available. The call to open in the OpenFile function will fail. When getFirstChar is called within the try block, an exception will be thrown by the IASSERTSTATE macro. This exception will be caught by the catch statement in main, and the output will look something like this:

    Type of exception is: IInvalidRequest
    Location of exception is: iopen.C
    Exception is recoverable

Using Throw Macros
Interpreting Exceptions
Using try and catch
Rethrowing Exceptions
Deriving Your Own Exceptions
Tracing Exceptions

The Exceptions Mechanism
Using Exceptions