Capture list item by index

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 size of the list.

If I execute this code I will get a IndexOutOfBoundsException .

What is the best deal for this case?

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

    
asked by anonymous 24.03.2017 / 15:00

2 answers

1

Unless you have a good reason for doing so, you do not have to capture a IndexOutOfBoundsException , most of the native java exceptions serve only as a warning to the programmer about issues that need to be fixed, not captured .

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

As for capturing RunTimeException , there's a other question here on the site that explains why you should avoid and some situations that may occur when catching more generic exceptions like this or Exception .

    
24.03.2017 / 18:52
1

For your case the best would be an if before myList.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
    }
}
    
24.03.2017 / 15:45