Example of Basic Exception Handling


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

The following example illustrates the basic use of try, catch, and throw. The program prompts for numerical input and determines the input 's reciprocal. Before it attempts to print the reciprocal to standard output, it checks that the input value is nonzero, to avoid a division by zero. If the input is zero, an exception is thrown, and the catch block catches the exception. If the input is nonzero, the reciprocal is printed to standard output.

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

// This example illustrates the basic use of
// try, catch, and throw.

#include <iostream.h>
#include <stdlib.h>
class IsZero { /* ... */ };
void ZeroCheck( int i )
{
         if (i==0)
                throw IsZero();
}
void main()
{
         double a;

         cout << "Enter a number: ";
         cin >> a;
         try
         {
              ZeroCheck( a );
              cout << "Reciprocal is " << 1.0/a << endl;
         }
         catch ( IsZero )
         {
              cout << "Zero input is not valid" << endl;
              exit(1);
         }
         exit(0);
}

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

This example could have been coded more efficiently by using informal exception handling. However, it provides a simple illustration of formal exception handling.

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