throws声明异常,throw抛出异常
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Throw {
public static void main(String[] args) {
//会报错
int[] arr ={1,2,3,4,5};
System.out.println(arr[10]); //越界
// ArrayIndexOutOfBoundsException
//throw ,throws
method1(); //空指针异常
int[] arr_AIOBE ={};
int max = getMax(arr_AIOBE);
}
//throws是告诉系统可能存在的异常,警告其小心一点!
private static void method1() throws NullPointerException {
int[] arr =null;
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
public static int getMax(int[] arr)
{
if(arr.length==0 || arr == null)
{
System.out.println("Error!");
throw new RuntimeException();
//有不正常操作,造一个异常来终止操作!
}
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if(arr[i]> max)
{
max = arr[i];
}
}
return max;
}