java中異常的拋出:throw throws


java中異常的拋出:throw throws

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聲明將異常拋出給更上一層的調用者(此方法無法處理異常,將異常再次拋出)

nice ,馬飛~

例如:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM