Handling Errors and Exceptions 727
20
intArray[7] okay...
intArray[8] okay...
intArray[9] okay...
intArray[10] okay...
intArray[11] okay...
intArray[12] okay...
intArray[13] okay...
intArray[14] okay...
intArray[15] okay...
intArray[16] okay...
intArray[17] okay...
intArray[18] okay...
intArray[19] okay...
Unable to process your input!
Done.
Listing 20.4 presents a somewhat stripped-down Arrayclass; however, this time
exception handling is added in case the array goes out of bounds.
On line 24, a new class,xBoundary, is declared within the declaration of the outer class
Array.
This new class is not in any way distinguished as an exception class. It is just a class the
same as any other. This particular class is incredibly simple; it has no data and no meth-
ods. Nonetheless, it is a valid class in every way.
In fact, it is incorrect to say it has no methods because the compiler automatically
assigns it a default constructor, destructor, copy constructor, and the assignment operator
(operator equals); so it actually has four class functions, but no data.
Note that declaring it from within Arrayserves only to couple the two classes together.
As discussed on Day 16, “Advanced Inheritance,”Arrayhas no special access to
xBoundary, nor does xBoundaryhave preferential access to the members of Array.
On lines 63–70 and 72–79, the offset operators are modified to examine the offset
requested, and if it is out of range, to throw the xBoundaryclass as an exception. The
parentheses are required to distinguish between this call to the xBoundaryconstructor
and the use of an enumerated constant.
In line 90, the main part of the program starts by declaring an Arrayobject that can hold
20 values. On line 91, the keyword trybegins a tryblock that ends on line 98. Within
that tryblock, 101 integers are added to the array that was declared on line 90.
On line 99, the handlerhas been declared to catch any xBoundaryexceptions.
In the driver program on lines 88–105, a tryblock is created in which each member of
the array is initialized. When j(line 93) is incremented to 20, the member at offset 20 is
ANALYSIS