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.
-
have you tried to debug it?Scary Wombat– Scary Wombat2014-02-03 07:12:21 +00:00Commented Feb 3, 2014 at 7: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– Paul Hicks2014-02-03 07:13:50 +00:00Commented Feb 3, 2014 at 7:13
Add a comment
|
1 Answer
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.