March, 1996 - Vol. 3 No. 3


Listing C: An exception in action

#include <iostream.h>

////// exception message objects /////////

class exception_base {
public:
   virtual const char* message() const =0;
   virtual ~exception_base() {};
   };

class simple_exception : public exception_base {
   const char* s;
public:
   simple_exception (const char* message) : s(message) {}
   const char* message() const { return s; };
   };

/// some classes to play with ///

class B {
   int x;
public:
   B (int x);
   ~B();
   };

B::B (int x)
  : x(x)
  {
  if (x < 0)  //a pre-condition check
     throw simple_exception ("B's constructor fails");
  cout << "Object B constructed at " << (void*)this << endl;
  }

B::~B()
  {
  cout << "Destructed a B object at " << (void*)this 
       << endl;
  }

class C {
   B sub_1;
   B sub_2;
   B sub_3;
public:
   C (int x, int y, int z);
   ~C();
   };

C::C (int x, int y, int z)
  : sub_1(x), sub_2(y), sub_3(z)
  {
  cout << "in the body of C's constructor with parameters ("
       << x << ',' << y << ',' << z << ")\n";
  }

C::~C()
  {
  cout << "destructing an object of type C\n";
  }

///////  The main program ///////

void bar (int x, int y, int z)
  {
  C mort (x,y,z);
  cout << "I constructed an object of type C named mort.\n";
  }


void foo (int x, int y, int z)
  {
  try {
     cout << "entering foo.\n";
     B local (56);
     bar (x,y,z);
    }
  catch (int errcode) {
     // note:  this catch block doesn't help me; it doesn't
     // match the error thrown in the example.
     cout << "Caught error code #" << errcode << endl;
    }
  }

int main()
  {
  try {
     foo (4,5,6);    //this one works.
     foo (9,-1,7);   //this one fails.
     }
  catch (exception_base& e) {
     cout << "caught an error: " << e.message() << endl;
    }
  return 0;
  } 

Return to "C++ Language basics - Exception handling: Understanding dynamic scope and stack unwinding"


Copyright (c) 1996 The Cobb Group, a division of Ziff-Davis Publishing Company. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis Publishing Company is prohibited. The Cobb Group and The Cobb Group logo are trademarks of Ziff-Davis Publishing Company.