📌  相关文章
📜  java.lang.arrayindexoutofboundsexception - Java (1)

📅  最后修改于: 2023-12-03 14:42:20.844000             🧑  作者: Mango

Java.lang.ArrayIndexOutOfBoundsException

Introduction

Java.lang.ArrayIndexOutOfBoundsException is an exception in Java that is thrown when an array is accessed with an invalid index. The cause of this exception is that the index being accessed is either negative or greater than or equal to the size of the array.

Understanding the Exception

To better understand this exception, let's take a look at some code that can cause it:

int[] nums = {1, 2, 3};
System.out.println(nums[3]);

In the above code, an array of integers is created with three elements. However, on the second line of code, we try to access the fourth element of the array by using an index of 3. Since the array only has three elements, this results in an ArrayIndexOutOfBoundsException.

Handling the Exception

To handle this exception, you can use a try-catch block. Here's an example:

int[] nums = {1, 2, 3};
try {
    System.out.println(nums[3]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid index");
}

In the code above, we've enclosed the line of code that might cause the exception in a try-catch block. If the exception occurs, the catch block will be executed, and the message "Invalid index" will be printed to the console.

Conclusion

Java.lang.ArrayIndexOutOfBoundsException is a common exception in Java that occurs when an invalid index is used to access an array. It's important to handle this exception properly by using a try-catch block to prevent your program from crashing.