C++ throw exceptions out of class

Description

C++ throw exceptions out of class

#include <iostream>
using namespace std;
class Measure//from   ww w.  j a va2 s .c  o m
{
   private:
   int feet;
   float inches;
   public:
   class InchesEx { };         //exception class
   Measure()
   { feet = 0; inches = 0.0; }
   Measure(int ft, float in)
   {
      if(in >= 12.0)           //if inches too big,
         throw InchesEx();     //throw exception
      feet = ft;
      inches = in;
   }
   void getdist()              //get length from user
   {
      cout << "\nEnter feet: ";  cin >> feet;
      cout << "Enter inches: ";  cin >> inches;
      if(inches >= 12.0)       //if inches too big,
         throw InchesEx();     //throw exception
   }
   void showdist()
      { cout << feet << "\'-" << inches << '\"'; }
};
int main()
{
      try
      {
         Measure dist1(17, 3.5);    //2-arg constructor
         Measure dist2;             //no-arg constructor
         dist2.getdist();            //get distance
         s
         cout << "\ndist1 = ";  dist1.showdist();
         cout << "\ndist2 = ";  dist2.showdist();
      }
      catch(Measure::InchesEx)      //catch exceptions
      {
         cout << "\nInitialization error: inches value is too large.";
      }
      cout << endl;
      return 0;
}



PreviousNext

Related