Java基础 抛出异常(throws 和 throw)

发布时间 2023-10-21 17:16:55作者: 嘎嘎鸭2

throws:写在方法定义处,表示声明一个异常,告诉调用者,使用本方法可能会有哪些异常(编译时异常:必须要写;运行时异常:可以不写)

语法:

public  void  方法 ()  throws  异常类名1 ,  异常类名2 ... {

}

 

 

throw:写在方法内,表示结束方法。用来手动抛出异常对象,把异常对象交给调用者处理,方法中下面的代码不再执行了

语法:

public  void  方法 ()  {

      throw  new  NullPointerException () ;

}

eg:

public static void main(String[] args) {
int[] arr = null;
int max = 0;
try {
max = getMax(arr);
} catch (NullPointerException e) {
System.out.println("空指针异常");
}

System.out.println(max);
}

public static int getMax(int[] arr) {
if(arr == null){
//手动创建一个异常对象,并把这个异常交给方法的调用者处理
//此时方法就会结束,下面的代码不会再执行了
throw new NullPointerException();
}

int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}