Java Reference
In-Depth Information
Let's take a look at a quick example. Suppose that we have implemented our baseball statistics
package from Chapter 2 . But when we start working on the implementation of calculating the
batting average for a player, we realize that the average is meaningless unless there are a suf-
ficient number of at-bats. If someone asks for the average of a player with fewer than the min-
imum number, we don't want to return an average; instead, we will return an exception that
will indicate that this mistake has taken place. The resulting code might look something like:
package examples;
public class BatterImpl implements Batter {
private int atBats;
private int hits;
...
public float getAverage() throws NotEnoughAtBatsException {
if (atBats < 10) {
throw new NotEnoughAtBatsException("Insufficient at bats",
10 - atBats);
}
return ((float)hits / (float)atBats);
}
}
The usual return value of the getAverage() method is the number of hits divided by the num-
ber of at-bats. But if the batter in question has fewer than 10 at-bats, we send a different an-
swer. In such a case, we throw an exception (in this case the NotEnoughAtBatsException )
that is a different kind of object than the float that is returned in the usual case.
The object that is thrown when the number of at-bats is less than 10 would be an instance of a
class something like:
package examples;
public class NotEnoughAtBatsException extends Exception {
private static final long serialVersionUID = 1L;
private int atBatsNeeded;
public NotEnoughAtBatsException(String message, int currentBats) {
super(message);
atBatsNeeded = currentBats;
}
int getNeeded(){
Search WWH ::




Custom Search