Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Exercises

  1. Create a class with member functions that throw exceptions. Within this class, make a nested class to use as an exception object. It takes a single char* as its argument; this represents a description string. Create a member function that throws this exception. (State this in the function’s exception specification.) Write a try block that calls this function and a catch clause that handles the exception by printing out its description string.
  2. Rewrite the Stash class from Chapter XX so it throws out-of-range exceptions for operator[].
  3. Write a generic main( ) that takes all exceptions and reports them as errors.
  4. Create a class with its own operator new . This operator should allocate 10 objects, and on the 11th “run out of memory” and throw an exception. Also add a static member function that reclaims this memory. Now create a main( ) with a try block and a catch clause that calls the memory-restoration routine. Put these inside a while loop, to demonstrate recovering from an exception and continuing execution.
  5. Create a destructor that throws an exception, and write code to prove to yourself that this is a bad idea by showing that if a new exception is thrown before the handler for the existing one is reached, terminate( ) is called.
  6. Prove to yourself that all exception objects (the ones that are thrown) are properly destroyed.
  7. Prove to yourself that if you create an exception object on the heap and throw the pointer to that object, it will not be cleaned up.
  8. (Advanced). Track the creation and passing of an exception using a class with a constructor and copy-constructor that announce themselves and provide as much information as possible about how the object is being created (and in the case of the copy-constructor, what object it’s being created from). Set up an interesting situation, throw an object of your new type, and analyze the result.
Contents | Prev | Next


Contact: webmaster@codeguru.com
CodeGuru - the website for developers.
[an error occurred while processing this directive]