user3210880
user3210880

Reputation: 29

Java Exception Handling custom class

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.

Upvotes: 2

Views: 98

Answers (1)

mrjink
mrjink

Reputation: 1129

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.

Upvotes: 1

Related Questions