DEV Community

Discussion on: how to fix Index was outside the bounds of the array error?

Collapse
 
katnel20 profile image
Katie Nelson

If you are intentionally accessing something outside the array, put the code in a try/catch block:

try {
    // put code here
}
catch(IndexOutOfRangeException ex)
{
    // handle error here
}
Collapse
 
waelelsayegh1 profile image
Wael El-Sayegh

Nope, it is not intentionally the purpose here is only to check the element neighbors only

Collapse
 
peledzohar profile image
Zohar Peled

Never attempt to catch an IndexOutOfRangeException when using arrays. This exception can be avoided simply by making sure your index is within the range - which in arrays means larger than -1 and smaller than array.Length.

For more information, read Eric Lippert's blog post entitled Vexing Exceptions