C++ examples for Class:Exception Class
Throw exceptions out of Measure class
#include <iostream> using namespace std; class Measure/*from ww w . j a va 2 s .com*/ { 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 distances 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; }