2

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.

2
  • have you tried to debug it? Commented 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. Commented Feb 3, 2014 at 7:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.