Capture list item by index

Asked

Viewed 86 times

1

I have the code:

for(int i = 0; i < 99999; i++) {
    minhaLista.get(i + x); //x é int e possui um valor qualquer
}

At some point the sum of i + x results in a value greater than the list size.

If you execute this code I will receive a IndexOutOfBoundsException.

What is the best treatment for this case?

I should check every iteration if (i + x) < minhaLista.size()? Or should I capture the IndexOutOfBoundsException?

2 answers

1

For your case the best would be an if before the minhalista.get(i + x);

for(int i = 0; i < 99999; i++) {
    if((i + x) < minhaLista.size()){
        minhaLista.get(i + x); //x é int e possui um valor qualquer
    }
}
  • This is one of the options I put to the question. The question is: why check every iteration instead of capturing the Exception?

  • An exception as the name already says and an exception, is should be treated as such, in its case amenos that x = 0 the Indexoutofboundsexception will always be launched.

1


Unless you have a good reason to, there’s no point in capturing a IndexOutOfBoundsException, most native java exceptions serve only to alert the programmer about problems that must be fixed, not to be captured.

You yourself answered the question, the most plausible solution is to check if the sum does not exceed minhaLista.size() -1, this already solves the problem without having to mess with unnecessary catches, leaving the code simpler.

In relation to capturing RunTimeException, there’s a another question here on the site that explains why one should avoid and some situations that may occur when capturing more generic exceptions like this or the Exception.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.