Page 603 - Introduction to Programming with Java: A Problem Solving Approach
P. 603

                14.8 CheckedExceptions 569
 public void removeStudent(int index)
{
}
// end removeStudent
try
{
}
students.remove(index);
catch (IndexOutOfBoundsException e)
{
}
System.out.println("Can't remove student because " +
index + " is an invalid index position.");
Figure 14.10a Using a try-catch structure for the removeStudent method
 public void removeStudent(int index)
{
}
// end removeStudent
if (index >= 0 && index < students.size())
{
}
else
{
}
students.remove(index);
Apago PDF Enhancer
System.out.println("Can't remove student because " +
index + " is an invalid index position.");
Figure 14.10b Using a careful-code strategy for the removeStudent method
Which solution is better—a try-catch mechanism or careful code? The solutions are about the same in terms of readability. With things being equal in terms of readability, go with the careful-code implemen- tation because it’s more efficient. Exception handling code is less efficient because it requires the JVM to instantiate an exception object and find a matching catch block.
14.8 Checked Exceptions
Let’s now look at checked exceptions. If a code fragment has the potential of throwing a checked exception, the compiler forces you to associate that code fragment with a try-catch mechanism. If there is no as- sociated try-catch mechanism, the compiler generates an error. With unchecked exceptions, you have a choice of how to handle them—a try-catch mechanism or careful code. With checked exceptions, there’s no choice—you must use a try-catch mechanism.
 

































































   601   602   603   604   605