Java Reference
In-Depth Information
This code looks a lot like our earlier test code. But where that earlier test code just checked to
see that the result of the call to getSlugging() was calculated correctly based on the values
of getTotalBases() and getAtBats() , the new test wraps the call to getTotalBases() in
a try block. If an exception is thrown, we check to make sure that the exception contains the
correct number of at-bats needed with respect to the number of at-bats the player already has.
All that is left is to see how our code should throw this exception. In our class that implements
the Batter interface, we might have something like:
package examples;
public class BatterImpl implements Batter {
private int atBats;
private int hits;
private int bases;
private int baseOnBalls;
private int sacrifices;
private String playerName;
...
public float getSlugging() throws NotEnoughAtBatsException {
if (atBats < 10){
throw new NotEnoughAtBatsException("Insufficient plate appearances",
10 - atBats);
}
return ((float)bases / (float)atBats);
}
In the method that calculates the slugging percentage, we first check to see whether the num-
ber of times the player has recorded an at-bat is greater than the minimum number. If it is
greater than the minimum, we continue and make the calculation. If it is not, we create a
new NotEnoughAtBatsException object, which contains the reason for the exception and the
number of at-bats needed by this player to reach the point at which the statistic is considered
meaningful. This object is then thrown back to the calling method, which can deal with it as it
wishes.
Use and Abuse
The code that we just saw catching an exception is a bit odd, but it is test code, so that's no
big surprise. In this case, the exception was in some sense expected, and what we wanted to
Search WWH ::




Custom Search