国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

java中異常的拋出:throw throws

2019-11-14 10:05:31
字體:
來源:轉載
供稿:網友

java中的異常拋出

語法:

public class ExceptionTest{    public void 方法名(參數列表) throws 異常列表{        //調用會拋出異常的方法或者拋出新的異常(throw new Exception();)    }}

注:throws 異常列表位于方法體之前,可拋出多種類型的異常,每個類型之間用逗號隔開

例如:

public class ExceptionTest{	public void divide(int one,int two) throws Exception{		if(two==0){			throw new Exception("兩數相除,除數不能為0!");		}		else{			System.out.PRintln("兩數相除,結果為:"+one/two);		}	}}

如果某個方法調用到了會拋出異常的方法,有以下兩種解決方案:

1.添加try-catch去捕獲異常進行處理

例如:

public class ExceptionTest {	public static void main(String[] args) {		try{			divide(5,0); // 調用了會拋出異常的方法divide();		}catch(Exception e){			System.out.println(e.getMessage());		}	}	public static void divide(int one,int two) throws Exception{		if(two==0){			throw new Exception("兩數相除,除數不能為0!");		}		else{			System.out.println("兩數相除,結果為:"+one/two);		}	}}運行結果:

兩數相除,除數不能為0!

2.添加throws聲明將異常拋出給更上一層的調用者(此方法無法處理異常,將異常再次拋出)

例如:

public class ExceptionTest {	public static void main(String[] args) throws Exception { //添加throws聲明		divide(5,0);	}	public static void divide(int one,int two) throws Exception{		if(two==0){			throw new Exception("兩數相除,除數不能為0!");		}		else{			System.out.println("兩數相除,結果為:"+one/two);		}	}}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 罗源县| 馆陶县| 乡宁县| 大庆市| 锡林郭勒盟| 吴堡县| 太仓市| 公主岭市| 顺平县| 株洲市| 鲁甸县| 琼中| 酉阳| 娄底市| 平远县| 景东| 天门市| 定陶县| 东港市| 淳化县| 无棣县| 长寿区| 鄂托克前旗| 七台河市| 陵水| 忻州市| 洞口县| 黑水县| 明星| 土默特右旗| 调兵山市| 穆棱市| 天气| 大悟县| 林西县| 都匀市| 彩票| 乌拉特前旗| 鹿邑县| 道孚县| 河池市|