3 minutes read

When your program processes an array, different types of exceptions may occur. To avoid them, you should be aware of risky situations and stick to a set of commonly used practices. Now, let's learn what exactly we are dealing with here.

NullPointerException

As you probably know by now, an array is a reference type, which means its variable can be null and that may lead to NPE.

val numbers: IntArray? = null
val size = numbers!!.size // It throws NPE

We will not dwell on that, since we suppose that you are already familiar with NPEs and ways of avoiding them by means of additional checks in your code:

val size = if (numbers == null) 0 else numbers.size

NegativeArraySizeException

If you try to create an array with a negative size, your code will compile successfully, but the respective line will throw NegativeArraySizeException while executing.

val negSize = -1
val numbers = IntArray(negSize) // an exception here

It's not very likely that you'll face this exception as a developer, but it makes sense to keep it in mind. To avoid it, simply do not use variables that can have a negative size when setting the size of an array.

An array may have a size greater than or equal to zero. If this is the case, the code will compile successfully and will not throw NegativeArraySizeException at runtime.

ArrayIndexOutOfBoundsException

This is a fairly common exception, which occurs while working with arrays. It is caused by attempting to access a nonexistent element of the array.

val array = intArrayOf(1, 2, 3) // an array of ints
val n1 = array[2] // n1 is 3
val n2 = array[3] // Exception

In this code, the last line throws ArrayIndexOutOfBoundsException, since the last index of the array in question is 2.

ArrayIndexOutOfBoundsException

The code will throw the same exception if we try accessing an element with a negative index:

array[0];  // OK
array[-1]; // Exception

To avoid ArrayIndexOutOfBoundsException, we may check if the given index belongs to the interval [0, size - 1].

For example, let's take a look at a program displaying an array element based on the index provided in the input. If the index is out of bounds, the program prints a message instead of throwing an exception.

fun main() {
    val hardCodedArray = intArrayOf(3, 2, 4, 5, 1)
    val index = readln().toInt()
    if (index < 0 || index > hardCodedArray.size - 1) {
        println("The index is out of bounds.")
    } else {
        println(hardCodedArray[index])
    }
}

Here are some possible inputs and the corresponding outputs of the program:

  • the index is 0, the program outputs "3";

  • the index is 1, the program outputs "2";

  • the index is 4, the program outputs "1";

  • the index is -1, the program outputs "The index is out of bounds.";

  • the index is 5, the program also outputs "The index is out of bounds."

That is how we can avoid ArrayIndexOutOfBoundsExceptions by using a conditional statement and the size property of an array.

StringIndexOutOfBoundsException

Since a string can be considered as a sequence of characters, a similar exception may occur when accessing a nonexistent element of a string. It is called StringIndexOutOfBoundsException.

val string = "string"
val ch = string[6] // Exception StringIndexOutOfBoundsException

Exception StringIndexOutOfBoundsException

To avoid this error, it is necessary to check whether the requested index is less than or equal to the length of line minus 1:

fun main() {

    val string = "string"
    val index = readln().toInt()
    if (index <= string.length - 1)
        println(string[index])
    else
        println("The check works, there is no exception.")
}

example of program output to the console

And here is the case when the check will work and we will avoid an exception:

output of the program to the console in case of exception handling

Be careful when querying the string index; a small check will help you avoid an error and prevent the application crash at runtime.

Conclusion

We have considered four types of array exceptions:

  • NullPointerException;

  • NegativeArraySizeException, which you may face when you are creating an array with a negative size;

  • ArrayIndexOutOfBoundsException, which occurs when you try accessing a nonexistent element;

  • StringIndexOutOfBoundsException, which occurs when you try accessing a string character at an index outside the length of the string.

As a developer, you need to keep in mind what exceptions you may face and, of course, be aware of basic ways of avoiding them.

53 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo