Reputation: 1280
What would be a good way to handle ArrayIndexOutOfBoundsException
for this case. Or ignore it?
public Attribute getAttribute (int index) {
return attributes.get(index);
}
A bug like this should not happen. The amount of Attributes are fixed in the project. Meaning I always know how many there are. I have a HashMap<String, String>
with their name and description
Somewhat follow up from:
Throw Exception or prevent it?
What would be an acceptable error handling of this situation? Or is it completely unnecessary?
Upvotes: 0
Views: 130
Reputation: 40386
If this should not happen as per the invariants and preconditions of the method, there is no real need to handle the exception. If you want to check to be make sure no bugs crop up during development, typically you would use assert
for something like this:
public Attribute getAttribute (int index) {
assert(index >= 0 && index < attributes.size());
return attributes.get(index);
}
Use assert
to make sure that preconditions and invariants are not violated. assert
shouldn't be used for checking of "normal" error conditions, but it is appropriate for debug / development sanity checks. It self-documents your assumptions. Also, it will allow a bug to be caught here, rather than at some vague higher level where an exception is eventually caught. This can help you pinpoint problems quicker.
For more information, some explanation and examples, check out programming with assertions.
There is also a related question at Avoiding != null statements - related in that the answer discusses overly aggressive checking of assumptions, and how to deal with them effectively; a good read.
However: It's important to note that your method is public
. The implication here is that anybody can call this. Perhaps you will even use this code in another program in the future. You will want to consider that when deciding whether or not you want to throw the AIOOB. If you do, I would just throw it out of the method, and document the method as throwing it if index
is out of range. It depends on your situation, really.
Also as Christian Hujer mentions in the comments below, a good set of test suites will help make sure your code never surprises you with any bugs here in the first place.
Upvotes: 1