Lab 8 - Exception Handling

Due: 10:00am on Wednesday

The purpose of this lab is to add exception handling to the DoubleList class used in Lab 5

Copy your solution for Lab 5 or the posted solution for Lab 5 (list.cpp) to a file called lab8.cpp. In lab8.cpp, you are going to add an index operator and exceptions.

First, add two exception classes above the DoubleList class definition:

Next, go through the DoubleList class and add a throw list for OutOfMemory to all member functions and constructors that allocate an array (use the new command). Remember to do this for both the prototypes and function bodies. Then, for all portions of the code that use the new command, throw an OutOfMemory exception if the new command fails to allocation memory.

Finally, add an index operator to the class. Have a throw list for the index operator that will indicate the function may throw the InvalidIndex exception class. Inside the body for the index operator, if the given index is less than 0 or greater than size - 1, through an InvalidIndex exception.

Update your main() function to the following main() function:

int main()
{
  int index;
  bool badIndex = true;
  double tmp1[] = {4.5, 6.5, 2.3, 1.2};
  double tmp2[] = {5.2, 4.3, 7.1, 8.5, 3.7, 2.8};
  DoubleList a, b(tmp1, 4), c(tmp2, 6);

  // This calls the assignment operator. Catch any allocation error that occurs
  try {
    a = c;
    cout << "Value of a after using a = c (assignment operator):" << endl;
    cout << a << endl << endl;
  } catch(OutOfMemory) {
    cout << "Could not allocate array to a.\n";
  }

  // Call concatenation and then assignment. Both could trigger allocation 
  // errors, but there's no way to tell them apart using just a flag class
  try {
    a = b + c;
    cout << "Value of a after using a = b + c:" << endl;
    cout << a << endl << endl;
  } catch(OutOfMemory) {
    cout << "Could not allocate array.\n";
  }

  // This loop will keep asking the user for an index until they give a
  // valid index. We'll use the lack of an exception from the index operator
  // as an indicator of a good index.
  while(badIndex)
  {
    cout << "Enter an index number for a: ";
    cin >> index;
    try {
      cout << "a[" << index << "] is ";
      cout << a[index];
      cout << endl;
      badIndex = false; // We'll only get to this line if the index is good
    } catch(InvalidIndex) {
      cout << "invalid. Please try again.\n";
    }
  }

  return 0;
}
It will be difficult to trigger the OutOfMemory exception on Sleipnir, but this main function will let you test that you have done the InvalidIndex exception correctly. It should keep asking for a new index until you give an index between 0 and 9.

Email your completed lab8.cpp to me.