在学习毕向东老师的课程时遇到的问题:
当把
if (arr==null) { throw new NullPointerException("数组不能为空!"); }
放在代码里的不同位置时,数组不能为空!这段字符在最后有时会显示有时不会。
如下:
class Demo
{
public int method(int [] arr,int index)
{
if (index>=arr.length)
{
throw new ArrayIndexOutOfBoundsException("数组角标越界!");
}
if (index<0)
{
throw new ArrayIndexOutOfBoundsException("数组角标不能为负数");
}
if (arr==null)
{
throw new NullPointerException("数组不能为空!");
}
return arr[index];
}
};
class ExceptionDemo1
{
public static void main(String[] args)
{
int[] arr = new int[3];
new Demo().method(null,3);
}
};
结果如下:
当把代码移到方法的首行时:
class Demo
{
public int method(int [] arr,int index)
{
if (arr==null)
{
throw new NullPointerException("数组不能为空!");
}
if (index>=arr.length)
{
throw new ArrayIndexOutOfBoundsException("数组角标越界!");
}
if (index<0)
{
throw new ArrayIndexOutOfBoundsException("数组角标不能为负数");
}
return arr[index];
}
};
class ExceptionDemo1
{
public static void main(String[] args)
{
int[] arr = new int[3];
new Demo().method(null,3);
}
};
结果如下:
将这段代码放在两个If中间也是不能显示出:数组不能为空!
欢迎在评论区帮我分析一下,我是新手。谢谢!