Java数组超出界限的异常处理示例
在Java中,当你尝试访问一个数组超出其边界的位置时,会抛出ArrayIndexOutOfBoundsException
异常。
以下是一个详细的异常处理示例:
public class ArrayBoundExceptionExample {
// 创建一个长度为5的数组
int[] array = new int[5];
// 正确索引的情况
try {
System.out.println(array[0]); // 输出:0
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: " + e.getMessage()); // 输出:Error: Index out of range
}
// 超出界限的索引情况
try {
System.out.println(array[5]); // 这会抛出ArrayIndexOutOfBoundsException异常
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: " + e.getMessage()); // 输出:Error: Index out of range
}
}
在这个示例中,我们首先创建了一个长度为5的数组。然后尝试访问超出数组界限(索引为5)的位置。
如果尝试访问超出界限的位置,会抛出ArrayIndexOutOfBoundsException
异常。在示例中,我们捕获了这个异常并打印出错误信息。
还没有评论,来说两句吧...