throw与throws

throw

throw出现在函数体中,它的作用就是一定触发一种异常,一定要写在try...catch里

//throw new 错误类型("出错啦")
throw new NegativeArraySizeException("出错啦") ;

throws

throws出现在函数头,它表示一种可能会出现的异常,但是也可能不会出现,捕获到异常后交给try...catch处理

static void pop() throws 错误类型{//定义方法并设置可能会报出的错误类型
int[] arr = new int[-3];//设置错误代码,(数组个数设置为-3)
}
public static void main(String args[]){
try{
    pop();//调用方法
}catch(错误类型 e){//处理
System.out.println(“报错”)
}
}

甚至可以设置多种可能会报出的异常

static void pop() throws 错误类型1,错误类型2,错误类型3{//定义方法并设置可能会报出的错误类型
int[] arr = new int[-3];//设置错误代码,(数组个数设置为-3)
}
public static void main(String args[]){
try{
    pop();//调用方法
}catch(错误类型1 e){//处理
System.out.println(“报错”)
}catch(错误类型2 e){//处理
System.out.println(“报错”)
}catch(错误类型3 e){//处理
System.out.println(“报错”)
}
}
原文地址:https://www.cnblogs.com/wandn/p/14819055.html