Java Reference
In-Depth Information
do was to test to make sure that the exception was thrown in the right circumstances and make
sure that the fields of the exception agreed with the data that was held in the Batter object.
A more usual catch clause would try to deal with the exceptional condition. As we will see
in Chapter 9 , there are some exceptions that can be corrected in the program, whereas others
might need to generate a new exception or raise the issue to the user. If we were building a
user interface for our baseball statistics package, for example, we would certainly want to in-
dicate in the batting statistics for a player when there were insufficient at-bats for an average.
But we might also want to make sure that we don't call any of the methods that could throw
the exception on a batter once it has already been thrown; we can stop our processing of such
a player early and move on to the next.
Properly used, the Java exception mechanism can allow a program to structure the error-hand-
ling code in a different location than the mainline code. So in our code that prints out the bat-
ting statistics for a player, we could make calls to the Batter object and not have any error
code gumming up the works as we were doing our formatting. Instead, all of the error hand-
ling would go to the end of the try statement in the catch clause; the resulting code would
look something like:
public class Formatter {
...
public static void Format(Batter toFormat){
System.out.print(toFormat.getName());
System.out.print("\t");
try {
System.out.print(toFormat.getAverage());
System.out.print("\t" + toFormat.getOBP());
System.out.print("\t" + toFormat.getSlugging());
System.out.print("\t" + toFormat.getAtBats());
System.out.println("\t" + toFormat.getTotalBases());
} catch (NotEnoughAtBatsException e){
System.out.println("\t" + "Not enough at-bats to be significant");
}
}
}
One common abuse of the Java exception mechanism is to use it as a more verbose variation
of the C-language convention of returning an impossible value that is checked immediately
after the call. On this approach, the previous code would look like:
Search WWH ::




Custom Search