Reputation: 151
If I have a method like this:
public Object getObject(int i) {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
} else {
return
}
}
Is this the best way to deal with array index out of bounds errors, and what should I return in the else statement, null?
Upvotes: 0
Views: 5405
Reputation: 95998
There is no absolute answer for this question, it depends on many things. However, if null
is not a legal value, I would return null
, if it's legal value I would throw
an exception.
/**
* ...
* @return The element at index i, null if out of bounds.
*/
public Object getObject(int i) {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
}
return null;
}
Or if null
is a legal value:
public Object getObject(int i) throw IndexOutOfBoundsException {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
}
throw new IndexOutOfBoundsException();
}
Upvotes: 3
Reputation: 1194
Its true there is no such thing like "best way" but you can handle exceptions by thinking what can cause them not to go to that point atleast.
public Object getObject(int i)
{
if(objectList == null || ojbectList.size()<=i)
return null;
if (i >= 0 && i < objectList.size())
{
return objectList.get(i);
}
}
Upvotes: 0
Reputation: 14549
I would throw an exception when the method is called with an illegal index. It does not make much sense to return anything for illegal calls.
Code would look like this:
public Object getObject(int i) {
return objectList.get(i);
}
Furthermore returning null
pollutes other code with boilerplate null-checks.
Finally you're in good neighborhood with Java's List specification of List.get(int) when raising IndexOutOfBoundsException
in such cases.
Upvotes: 0
Reputation: 17595
You could implement the Null Object pattern.
Or you could implement a clamp, i.e. if the index is negative then return element at index 0
or if it is greater than or equal to size then return element at index size-1
But in your particular case the best thing to do is to raise an exception. This is what List#get does per default, so just leave it like that.
The reason is that you are explicitly asking for the value of an element at a certain index, i.e you expect that it is available. If not then there must be something wrong with the logic you use to determine that index.
Upvotes: 0
Reputation: 66815
There is no such thing as "the best way", everything depends on your particular application. If "null" is somewhat recognizable (there are no nulls in your container) it can be an option. In some cases returning 0 may be the good option (when dealing with strictly positive number containers) and in others you could return element at i % size
(so your container is cyclic). In general - it is always risky to return anything when asked for non existing element.
The most "frequent" approach is to raise an exception instead of returning anything.
Upvotes: 1