Page 602 - Introduction to Programming with Java: A Problem Solving Approach
P. 602
568 Chapter 14 Exception Handling
The students.remove method call is dangerous because it might throw an unchecked exception, IndexOutOfBoundsException. If its index argument holds the index of one of the students’ ele- ments, then that element is removed from the students ArrayList. But if its index argument holds an invalid index, then an IndexOutOfBoundsException is thrown. This occurs, for example, if we use Figure 14.9’s StudentListDriver class as the driver. Note how the StudentListDriver class uses an index value of 6 even though there are only four students in the student list. The StudentListDriver and StudentList classes compile just fine, but when run, the students.remove method call throws an exception and the JVM terminates the program and prints the error message shown at the bottom of Figure 14.9.
/*************************************************************
*
StudentListDriver.java
Dean & Dean
This is the driver for the StudentList class.
*************************************************************/
*
*
*
public class StudentListDriver
{
public static void main(String[] args)
{
String[] names = {"Caleb", "Izumi", "Mary", "Usha"};
Apago PDF Enhancer
studentList.display();
studentList.removeStudent(6);
studentList.display();
// end main
StudentList studentList = new StudentList(names);
}
// end StudentListDriver
}
Output:
Caleb Izumi Mary Usha
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6,
Size: 4
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:390)
at StudentList.removeStudent(StudentList.java:43)
at StudentListDriver.main(StudentListDriver.java:17)
This argument value generates a runtime error.
Figure 14.9 Driver of StudentList class
Improve the removeStudent Method
Let’s now make the removeStudent method more robust by gracefully handling the case programs where it’s called with an invalid index. Figures 14.10a and 14.10b show two different robust robust. implementations for the removeStudent method. The first implementation uses a try-
catch mechanism and the second implementation uses careful code. These are the two strate- gies mentioned earlier for handling unchecked exceptions.
Make