Inheritance/Polymorphism  «Prev  Next»
Lesson 17 C++ Exceptions
Objective Recode ch_stack Class Constructors to throw Exceptions for Conditions

ch_stack Class Constructors throw Exceptions

Recode ch_stack Class Constructors to throw Exceptions for Conditions

Recode any one of the ch_stack class constructors so they throw exceptions for as many conditions that you think are reasonable.
An exception is an unexpected condition that a program encounters and cannot cope with. An example is floating-point division by zero. Usually the system aborts the running program. Bad dynamic_cast and typeid operations can be made to throw the exceptions bad_cast and bad_typeid, so the user can choose between dealing with the NULL pointer or catching an exception. C++ code is allowed to directly raise an exception in a try block by using the throw expression. The exception is handled by invoking the appropriate handler selected from a list found in the routine containing the try block. A simple example of this is:

vect::vect(int n){ 
 //fault tolerant constructor
  try {
     if (n < 1)
        throw(n);
        p = new int[n];
        if (p==0)
           throw ("FREE STORE EXHAUSTED");
  }
  catch (int n) {
     cerr << "Incorrect vector size: "
       << n << endl;
     exit(1);
  } //catches an incorrect size
  catch (const char* error) {
     cerr << error << endl;
     delete p [];
     exit (1);
  }// catches free store exhaustion
}

The catch looks like a function declaration with one argument and no return type. An ellipses signature that matches any argument is allowed:
Please note that older compilers may not support exceptions.

catch(...) //default action to be taken
{
   cerr << "Aborting program execution!" << endl;
   abort ();
}

Coding Exception - Exercise

Click the Exercise link below to recode any one of the ch_stack class constructors so they throw exceptions for as many conditions that you think are reasonable.
Coding Exception - Exercise