Java Reference
In-Depth Information
}
Solution 42: Thrown for a Loop
The program tests each element of the array tests with the thirdElementIsThree method. The
loop through this array is certainly not traditional: Rather than terminating when the loop index is
equal to the array length, the loop terminates when it attempts to access an array element that isn't
there. Although nontraditional, this loop ought to work. The thirdElementIsThree method returns
true if its argument has three or more elements and the third element is equal to 3. This is true for
two of the five int arrays in tests , so it looks as though the program should print 2 . If you ran it,
you found that it prints 0 . Surely there must be some mistake?
In fact, there are two mistakes. The first mistake is that the program uses the hideous loop idiom
that depends on an array access throwing an exception. This idiom is not only unreadable but also
extremely slow. Do not use exceptions for loop control; use exceptions only for exceptional
conditions [EJ Item 39]. To correct this mistake, replace the entire try - finally block with the
standard idiom for looping over an array:
for (int i = 0; i < tests.length; i++)
if (thirdElementIsThree(tests[i]))
successCount++;
If you are using release 5.0 or a later release, you can use the for-each construct instead:
for (int[] test : tests)
if (thirdElementIsThree(test))
successCount++;
As bad as the first mistake is, it alone is not sufficient to account for the observed behavior. Fixing
this mistake will, however, help us to find the real bug, which is more subtle. If we fix the first
mistake and run the program again, it fails with this stack trace:
Exception in thread "main"
 
 
Search WWH ::




Custom Search