抛出异常(新手)

这个目前还是处于懵逼状态,只是把写法写出来,明天老师还会细讲。

==================================================

public class yichanglx {
public static void main(String[] args) throws Exception {
//抛出异常你可以理解为在你做此项目的时候,你感觉这个地方有可能会出现异常,
//可以写上抛出异常,到最后可以给你自己一个提示,也可以给别人一个提示。
int arr[] = {0,2};
getArray(arr);
}

private static int getArray(int[] arr)throws Exception {
if (arr.length==0){
throw new Exception("");

}
return 1;
}
}
=======================================================
public class zylx2 {
public static void main(String[] args){
int[] arr = null;
try{
int i = getArray(arr);
}catch (Exception e ){
System.out.println(e);
}
}

private static int getArray(int[] arr) throws Exception {
if (arr == null){
throw new NullPointerException("数组不存在。");
}if (arr.length<3){
throw new ArrayIndexOutOfBoundsException("数组没有3这个索引");
}
return arr[3]+1;
}
}
posted @ 2019-03-22 21:47  浪子。  阅读(268)  评论(0编辑  收藏  举报