Validating a list: prefer explicit IllegalArgumentException over automatic ArrayIndexOutOfBounds?

Viewed 56

I have a class that is supposed to wrap around strings found in some input file. The contract is that this files contains multiple entries (separated by # chars), to be precise: at least two entries should come out of that file.

Now I could do this:

public MyWrapper(List<String> fileEntries) {
   if (fileEntries.size() < 2) { 
     throw new IllegalArgumentException("Not enough entries ...
   }

or I could just do:

public MyWrapper(List<String> fileEntries) {
   this.firstEntry = fileEntries.get(0);
   this.secondEntry = someMethodThatMergesAllRemainingEntries(fileEntries);

That second piece would throw ArrayIndexOutOfBound at some point.

My question is: is there some precedent in the Java standard library that could be seen as guidance? (similar to the Java standard library call requireNonNull() that tells us to maybe prefer to throw a NPE instead of IllegalArgumentException for null arguments).

Note: I am not asking "what would be better", both sides have their pros and cons (I am slightly tempted to prefer option 1, as that is simply shorter).

1 Answers

There are plenty of precedents for #1.

For example, ArrayList performs its own explicit bounds checks and throws IndexOutOfBoundsException with a descriptive messages (including both the offending index and the array size) instead of letting the underlying array access fail with its own exception (which in this example would happen to be a subclass of IndexOutOfBoundsException, but that's beside the point).

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/ArrayList.java#l1200

I personally would choose #1 over #2 in most circumstances, primarily because it allows me to be more explicit and provide a clear(er) exception message.

Related