Example of Using Constructors in Exception Handling


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

In the following example, an object of class DivideByZero is thrown by the function divide(). The constructor copies the string "Division by zero" into the char array errname. Because DivideByZero is a derived class of class Matherr, the catch block for Matherr catches the thrown exception. The catch block can then access information provided by the thrown object, in this case the text of an error message.

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

// This example illustrates constructors and
// destructors in exception handling.

#include <string.h>            // needed for strcpy
#include <iostream.h>
class Matherr { public: char errname[30]; };
class DivideByZero : public Matherr
{
public:
      DivideByZero() {strcpy (errname, "Division by zero");}
};
double divide(double a, double b)
{
      if (b == 0) throw DivideByZero();
      return a/b;
}

void main()
{
      double a=7,b=0;
      try {divide (a,b);}
      catch (Matherr xx)
      {
            cout << xx.errname << endl;
      }
}