/**
数组中常见的异常:
1.下角标越界:ArrayIndexOutOfBoundsException
原因 :因为使用的索引值没有在合理范围(0~数组的长度-1)之内
2.空指针异常:NullPointerException
原因 :只要调用属性和方法的那个值为null就会发生空指针异常
*/
public class ArrayExceptionTest {
public static void main(String[] args) {
//1.下角标越界:ArrayIndexOutOfBoundsException
int[] numbers = new int[2]; //0 ~ 1是可以的
// System.out.println(numbers[2]); 编译错误:超出了索引值的范围
// System.out.println(numbers[-1]);编译错误:超出了索引值的范围
System.out.println("----------------------------------------");
// 2.空指针异常:NullPointerException
String str = "aaa";
str = null;
// System.out.println(str.toUpperCase());编译错误: 因为str的内容为null
String[][] ps = new String[2][3];
// System.out.println(ps[0][0].toUpperCase());编译错误: 因为ps[0][0]的内容为null
String[][] ps2 = new String[2][];//二维数组的元素的默认值为null
System.out.println(ps2[0][0]);//编译错误:因为ps2[0]为null
}
}
java数组常见异常:下标越界、空指针异常
最新推荐文章于 2024-05-08 18:00:47 发布