I am having trouble handling some exceptions. It would be great if you could point me to a direction so I can understand exceptions better as well as learning to handle exceptions more efficient. Through the commandline argument it splits a single string to 4 different strings and an error message handled by the exception will print out Expected 4 element but got 3 or any number of items such as Expected 4 elements but got 2.
Asked
Active
Viewed 93 times
2
-
have you tried to debug it? – Scary Wombat Feb 03 '14 at 07:12
-
What parameter are you passing as an inventory string? It needs to have exactly three quoted pipes to give you 4 parameters in each colon-separated row. – Paul Hicks Feb 03 '14 at 07:13
1 Answers
1
I would change the InventoryReader
to something like this:
for (String row : rows) {
String[] elements = row.split("\\|");
if (elements.length != 4) {
throw new ApplicationException("Expected 4 elements, got " + elements.length);
}
items[i++] = new Item(elements[0], elements[1], Integer.valueOf(elements[2]),
Float.valueOf(elements[3]));
}
Then you can be sure the number of items is what you expect, and you don't have to handle the ArrayIndexOutOfBoundsException
, since that can never occur.

mrjink
- 1,131
- 1
- 17
- 28