Card 04/ 08

GotchaDifficulty: Intermediate1 min

Reading the Exception That Names an Index You Never Wrote

A report that has worked for months throws on one customer. The index in the message is a number nothing in your code contains.

text
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 12
	at Report.monthName(Report.java:31)
java
String[] names = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

String monthName(int month) {
    return names[month];
}

Twelve names, indexes 0 to 11. The caller passed 12 because it had a month number rather than an offset, and December is the twelfth month and the eleventh index. The array did exactly what it was told.

The message is worth reading closely, because it carries both halves of the answer. Index 12 is what was asked for; for length 12 is what exists. If those two numbers are equal, something counted from one and indexed from zero. If the index is negative, a subtraction went below the start.

Convert at the boundary, not inside: take the month number from the caller and subtract one where it enters, so the rest of the method works in offsets and nothing else has to remember which convention it is in.