Java Reference
In-Depth Information
15.2 A More Complete ArrayIntList
In this section we will extend the ArrayIntList class to throw exceptions when pre-
conditions are violated and to include a more inclusive set of methods that parallel
the methods available for the built-in ArrayList<E> .
Throwing Exceptions
In the previous version of ArrayIntList , we documented the various preconditions
of the methods. It is a good practice to clearly specify the contract with potential
clients, but you shouldn't assume that clients will always obey the preconditions. As
we saw in Chapter 4, the convention in Java is to throw an exception when a precon-
dition is violated.
For example, consider the constructor that takes a capacity as a parameter:
// pre : capacity >= 0
// post: constructs an empty list with the given capacity
public ArrayIntList(int capacity) {
elementData = new int[capacity];
size = 0;
}
The precondition indicates that the capacity is not supposed to be negative. You
can go further than just documenting it by adding code to throw an exception. In this
case, it is appropriate to throw an IllegalArgumentException :
if (capacity < 0) {
throw new IllegalArgumentException();
}
You have the option to include a string that will be displayed with the exception.
In this case, it would be useful to tell the client the value that was being passed for
capacity :
if (capacity < 0) {
throw new IllegalArgumentException("capacity: " + capacity);
}
You should also mention the exception in the comments for the method. It is
important to mention exactly which type of exception will be thrown and under what
circumstances. Here, then, is the final version of the method with the extra code to
throw an exception when the precondition is violated:
// pre : capacity >= 0 (throws IllegalArgumentException if not)
// post: constructs an empty list with the given capacity
public ArrayIntList(int capacity) {
 
 
Search WWH ::




Custom Search