Example of Rethrowing an Exception


/************************************************************************
*

In the following example, catch(FileIO) catches any object of type FileIO and any objects that are public base classes of the FileIO class. It then checks for those exceptions it can handle. For any exception it cannot handle, it issues a rethrow expression to rethrow the exception and allow another handler in a dynamically enclosing try block to handle the exception.

                                                                        *
************************************************************************/

// This example illustrates rethrowing an exception.

#include <iostream.h>
class FileIO
{
public:
      int notfound;
      int endfile;
      FileIO(); // initialize data members
      // the following member functions throw an exception
      // if an input error occurs
      void advance(int x);
      void clear();
      void put(int x, int y);
};
//      .
//      .
//      .
void f()
{
      FileIO fio;
      try
      {
            // call member functions of FileIO class
            fio.advance (1);
            fio.clear();
            fio.put(1,-1);
      }

      catch(FileIO fexc)
      {
            if (fexc.notfound)
                  cout << "File not Found" << endl;
            else if (fexc.endfile)
                  cout << "End of File" << endl;
            else
                  throw;            // rethrow to outer handler
      }
      catch(...) { /* ... */ }      // catch other exceptions
}
main()
{
      try
      {
            f();
      }
      catch(FileIO) { cout << "Outer Handler" << endl; }
}

/************************************************************************
*

The rethrow expression can be caught by any catch whose argument matches the argument of the exception originally thrown. Note that, in this example, the catch(...) will not catch the rethrow expression because , when the rethrow expression is issued, control passes out of the scope of the function f() into the next dynamically enclosing block.

                                                                        *
************************************************************************/