Concepts of Programming Languages

(Sean Pound) #1

652 Chapter 14 Exception Handling and Event Handling


throw new NegativeInputException();
index = newGrade / 10;
try {
freq[index]++;
} //** end of inner try clause
catch(ArrayIndexOutOfBoundsException e) {
if (newGrade == 100)
freq [9]++;
else
System.out.println("Error - new grade: " +
newGrade + " is out of range");
} //** end of catch (ArrayIndex...
} //** end of while (true)...
} //** end of outer try clause
catch(NegativeInputException e) {
System.out.println ("\nLimits Frequency\n");
for (index = 0; index < 10; index++) {
limit_1 = 10 * index;
limit_2 = limit_1 + 9;
if (index == 9)
limit_2 = 100;
System.out.println("" + limit_1 + " - " +
limit_2 + " " + freq [index]);
} //** end of for (index = 0;...
} //** end of catch (NegativeInputException...
} //** end of method buildDist

The exception for a negative input, NegativeInputException, is defined
in the program. Its constructor displays a message when an object of the class
is created. Its handler produces the output of the method. ArrayIndexOutOf-
BoundsException is a predefined unchecked exception that is thrown by
the Java run-time system. In both of these cases, the handler does not include
an object name in its parameter. In neither case would a name serve any
purpose. Although all handlers get objects as parameters, they often are not
useful.

14.4.6 The finally Clause


There are some situations in which a process must be executed regardless of
whether a try clause throws an exception and regardless of whether a thrown
exception is caught in a method. One example of such a situation is a file that
must be closed. Another is if the method has some external resource that must
be freed in the method regardless of how the execution of the method termi-
nates. The finally clause was designed for these kinds of needs. A finally
clause is placed at the end of the list of handlers just after a complete try con-
struct. In general, the try construct and its finally clause appear as
Free download pdf