Kotlin ArrayIndexOutOfBoundsException

Introduction

In Kotlin, ArrayIndexOutOfBoundsException is an exception that occurs when you try to access an index of an array that is outside its valid range. This can happen if you try to access a negative index or an index greater than or equal to the array size.

Table of Contents

  1. What is ArrayIndexOutOfBoundsException?
  2. Common Scenarios Causing ArrayIndexOutOfBoundsException
  3. Examples of ArrayIndexOutOfBoundsException
  4. Preventing ArrayIndexOutOfBoundsException
  5. Handling ArrayIndexOutOfBoundsException
  6. Conclusion

1. What is ArrayIndexOutOfBoundsException?

ArrayIndexOutOfBoundsException is a runtime exception that is thrown when an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

2. Common Scenarios Causing ArrayIndexOutOfBoundsException

  • Accessing an index less than 0.
  • Accessing an index greater than or equal to the array size.
  • Iterating beyond the array length.
  • Incorrectly calculating the index.

3. Examples of ArrayIndexOutOfBoundsException

Example 1: Accessing a Negative Index

This example demonstrates accessing a negative index, which is not valid.

fun main() {
    val array = arrayOf(1, 2, 3)
    // Attempting to access a negative index
    println(array[-1])
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3

Example 2: Accessing Index Greater Than Array Size

This example demonstrates accessing an index greater than the array size.

fun main() {
    val array = arrayOf(1, 2, 3)
    // Attempting to access an index greater than the array size
    println(array[3])
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Example 3: Iterating Beyond Array Length

This example shows an error when iterating beyond the array length.

fun main() {
    val array = arrayOf(1, 2, 3)
    // Iterating beyond the array length
    for (i in 0..array.size) {
        println(array[i])
    }
}

Output:

1
2
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Example 4: Incorrect Index Calculation

This example demonstrates a common error in the index calculation.

fun main() {
    val array = arrayOf(1, 2, 3)
    val index = array.size
    // Incorrectly calculated index
    println(array[index])
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

4. Preventing ArrayIndexOutOfBoundsException

To prevent this exception, always ensure the index is within the valid range of the array.

Example 5: Validating Index

This example demonstrates checking the index before accessing the array.

fun main() {
    val array = arrayOf(1, 2, 3)
    val index = 2
    // Validating index
    if (index >= 0 && index < array.size) {
        println(array[index])
    } else {
        println("Index out of bounds")
    }
}

Output:

3

5. Handling ArrayIndexOutOfBoundsException

You can handle this exception using a try-catch block.

Example 6: Using try-catch

This example demonstrates handling the exception using a try-catch block.

fun main() {
    val array = arrayOf(1, 2, 3)
    try {
        // Attempting to access an out-of-bounds index
        println(array[3])
    } catch (e: ArrayIndexOutOfBoundsException) {
        println("Caught ArrayIndexOutOfBoundsException: ${e.message}")
    }
}

Output:

Caught ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Example 7: Safe Array Access with getOrNull

This example uses getOrNull to safely access array elements.

fun main() {
    val array = arrayOf(1, 2, 3)
    val element = array.getOrNull(3) ?: "Index out of bounds"
    println(element)
}

Output:

Index out of bounds

Conclusion

ArrayIndexOutOfBoundsException is a common runtime exception in Kotlin that occurs when accessing an invalid array index. By validating indices and using safe access methods, you can prevent and handle this exception effectively. Understanding these practices is essential for robust Kotlin programming.

Comments