数组的常见异常

1. 下标越界异常

2.  空指针异常

public class TestException {
    public static void main(String[] args) {
        // 数组下标越界异常:java.lang.ArrayIndexOutOfBoundsException: 10
        int[] i = new int[10];
/*        i[0] = 99;
        i[10] = 99;
        for( int m = 0;m<i.length;m++){
            System.out.println(i[m]);
        }
        
*/
        //空指针异常:java.lang.NullPointerException
        //第一种:
/*        boolean[] b= new boolean[3];
        b = null;// b为null原来指向数组的指针没有了 
        System.out.println(b[0]);
*/
        //第二种:
/*        String[] str = new  String[4];
        System.out.println(str[3].toString());//str[3]为对象本身为null  调用方法  也为空指针异常
*/
        
        //第三种:
/*        int[][] j = new int[3][];
        j[2][0] = 12; //本身为null无法赋值
*/
    }
}

猜你喜欢

转载自www.cnblogs.com/afangfang/p/12460530.html
今日推荐