22:
23: void OutOfMemory::PrintError()
24: {
25: cout << “Out of Memory!!” << endl;
26: }
27:
28: // Derived class to handle bad numbers
29: class RangeError : public Exception
30: {
31: public:
32: RangeError(unsigned long number){badNumber = number;}
33: ~RangeError(){}
34: virtual void PrintError();
35: virtual unsigned long GetNumber() { return badNumber; }
36: virtual void SetNumber(unsigned long number) {badNumber =
➥number;}
37: private:
38: unsigned long badNumber;
39: };
40:
41: void RangeError::PrintError()
42: {
43: cout << “Number out of range. You used “ ;
44: cout << GetNumber() << “!!” << endl;
45: }
46:
47: void MyFunction(); // func. prototype
48:
49: int main()
50: {
51: try
52: {
53: MyFunction();
54: }
55: // Only one catch required, use virtual functions to do the
56: // right thing.
57: catch (Exception& theException)
58: {
59: theException.PrintError();
60: }
61: return 0;
62: }
63:
64: void MyFunction()
65: {
66: unsigned int *myInt = new unsigned int;
67: long testNumber;
68:
69: if (myInt == 0)
70: throw OutOfMemory();
71:
870 Appendix D
32 0672327112_app_d.qxd 11/19/04 12:30 PM Page 870