throw與throws的區(qū)別?
throw與throws的區(qū)別?
throws---創(chuàng)建方法的時(shí)候,用來聲明方法拋出的異?!緬伋霎惓!?/p>
處理異常一般有2中情況
1.?有異常以后,我們可以直接通過try{}catch(){}來捕獲處理異常
public ?class ?Test{
????public ?void ?method(){
??????try{
????????????int a=10/0; ?// 出現(xiàn)異常 ?除數(shù)不能為0
????????????System.out.println(“a==”+a);
????????}catch(Exception ?e){
???????????????//處理異常
????????}
????}
}
2.?有異常以后,我們自己不想處理,可以聲明方法拋出異常,誰調(diào)用這個(gè)拋出異常的放啊事就去處理,如果還不想處理,就繼續(xù)向上一級(jí)拋出異常,一直沒有處理,那么java虛擬機(jī)將這個(gè)異常打印到控制臺(tái)。
拋出異常----throws
public ?class ?Test{
????????public ?void ?method() throws Exception {
????????????????int a=10/0; ?// 出現(xiàn)異常 ?除數(shù)不能為0
????????????????System.out.println(“a==”+a);
????????}
}
throws--是聲明方法拋出異常。
throw-- 手動(dòng)引發(fā)一個(gè)異?!居袝r(shí)候異常的存在是為了提醒用戶操作不當(dāng)】
public ?class ?Test{
???????private ?int ?intarr[]; ??
???????public ?Test(int size)throws Exception{
????????????If(size>=0){
????????????????//創(chuàng)建int型數(shù)組
????????????????intarr=new int[size];
????????????}else{
????????????????//為了提醒用戶的錯(cuò)誤操作我們手動(dòng)引發(fā)一個(gè)異常
????????????????throw??new Exception(“數(shù)字大小不能為負(fù)數(shù)”);
????????????}
????????}
???????public ?int[] ?getIntArray{
????????????return intarr;
????????????}
?}
throw---手動(dòng)引發(fā)一個(gè)異常,一旦引發(fā)以后,要么try{}catch(){}來捕獲處理異常,要么就throws拋出異常。