Handling Errors and Exceptions 733
20
21: // friend function
22: friend ostream& operator<< (ostream&, const Array&);
23:
24: // define the exception classes
25: class xBoundary {};
26: class xSize {};
27: class xTooBig : public xSize {};
28: class xTooSmall : public xSize {};
29: class xZero : public xTooSmall {};
30: class xNegative : public xSize {};
31: private:
32: int *pType;
33: int itsSize;
34: };
35:
36:
37: Array::Array(int size):
38: itsSize(size)
39: {
40: if (size == 0)
41: throw xZero();
42: if (size > 30000)
43: throw xTooBig();
44: if (size <1)
45: throw xNegative();
46: if (size < 10)
47: throw xTooSmall();
48:
49: pType = new int[size];
50: for (int i = 0; i < size; i++)
51: pType[i] = 0;
52: }
53:
54: int& Array::operator[](int offSet)
55: {
56: int size = GetitsSize();
57: if (offSet >= 0 && offSet < GetitsSize())
58: return pType[offSet];
59: throw xBoundary();
60: return pType[0]; // appease MFC
61: }
62:
63: const int& Array::operator[](int offSet) const
64: {
65: int mysize = GetitsSize();
66:
67: if (offSet >= 0 && offSet < GetitsSize())
68: return pType[offSet];
69: throw xBoundary();
LISTING20.6 continued