Java Reference
In-Depth Information
How It Works
To see how this really works, let's revisit our baseball statistics package that we started in
Chapter 2 . This seems like a simple package, so why would we worry about exceptions? We
push the hits and at-bats into the objects, get the statistics out, and that's it.
Except that we wouldn't want to have baseball statistics for players who had appeared only a
time or two. For statistics to make sense, there must be a floor on when you start to calculate
those statistics. Concentrating on the batting statistics, for example, we might decide that a
minimum of 10 at-bats need to be recorded by a player before we want to count any statistics
about the batting of that player. Otherwise, we will simply say that the player has not done
enough to get an answer when asked about, say, his batting average or on-base percentage.
To do this, we first have to define an exception that can be thrown when a player's statistics
are invalid. Earlier we saw a sketch of the NotEnoughAtBatsException class; now we will
look at one that we might actually use (in this case, adding the needed Javadoc):
package examples;
/**
* Exception thrown when a batter has not had enough attempts to make
* the batting statistics valid. The exception contains both a string
* indicating the reason for the exception, and the number of additional
* at-bats a player needs before the particular statistic is considered
* valid.
*
*/
public class NotEnoughAtBatsException extends Exception {
static final long serialVersionUID = 1;
private int atBatsNeeded;
/**
* Basic constructor, taking the reason and the number of
* additional at-bats needed for a statistic to be valid
* @param message
* @param needed
*/
public NotEnoughAtBatsException(String message, int needed) {
super (message);
atBatsNeeded = needed;
}
/**
* Returns the number of at-bats needed for this exception to
Search WWH ::




Custom Search