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

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

java中異常的拋出:throw throws

2019-11-14 09:58:55
字體:
來源:轉載
供稿:網友

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);		}	}}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 庐江县| 黑山县| 台东市| 商洛市| 正宁县| 广东省| 嵊州市| 白城市| 乐都县| 祁东县| 中宁县| 西华县| 凌海市| 辽源市| 临高县| 武隆县| 久治县| 新平| 融水| 盐山县| 丹寨县| 达州市| 凤翔县| 安吉县| 文昌市| 陵川县| 葫芦岛市| 乌恰县| 页游| 文昌市| 潞西市| 三都| 平顺县| 庄浪县| 广河县| 湖州市| 集贤县| 台湾省| 色达县| 偏关县| 桓仁|