1. 程式人生 > >Java異常處理的五個關鍵字

Java異常處理的五個關鍵字

異常:異常有的是因為使用者錯誤引起,有的是程式錯誤引起的,還有其它一些是因為物理錯誤引起的。
異常處理關鍵字:try、catch、finally、throw、throws
注意事項:
1、錯誤不是異常,而是脫離程式設計師控制的問題。
2、所有的異常類是從 java.lang.Exception 類繼承的子類。
3、異常類有兩個主要的子類:IOException 類和 RuntimeException 類。
4、Java有很多的內建異常類。
異常大致分類:
1、使用者輸入了非法資料。
2、要開啟的檔案不存在。
3、網路通訊時連線中斷,或者JVM記憶體溢位。

語法:

try{

//需要監聽的程式碼塊

}

catch(異常型別 異常名稱/e){

//對捕獲到try監聽到的出錯的程式碼塊進行處理

throw 異常名稱/e; //thorw表示丟擲異常

throw new 異常型別(“自定義”);

}

finally{

//finally塊裡的語句不管異常是否出現,都會被執行

}

修飾符 返回值 方法名 () throws 異常型別{  //throws只是用來宣告異常,是否丟擲由方法呼叫者決定

//程式碼塊

}

程式碼例子:(try與catch與finally)

publicclassExceptionTest{publicstaticvoid main(String[] args){Scanner input=newScanner(System.in);try{//監聽程式碼塊  
int a=input.nextInt();int b=input.nextInt();double sum=a/b;System.out.println(sum);}catch(InputMismatchException e){System.out.println("只能輸入數字");}catch(ArithmeticException e){System.out.println("分母不能為0");}catch(Exception e){//Exception是所有異常的父類 System.out.println("發生了其他異常");}finally{//不管是否出現異常,finally一定會被執行
System.out.println("程式結束");}}}

程式碼例子:(throw關鍵字)

import java.util.InputMismatchException;import java.util.Scanner;publicclassExceptionTest{publicstaticvoid main(String[] args){Scanner input=newScanner(System.in);try{//監聽程式碼塊  int a=input.nextInt();int b=input.nextInt();double sum=a/b;System.out.println(sum);}catch(InputMismatchException e){//catch(異常型別 異常名稱)  System.out.println("只能輸入數字");throw e;//丟擲catch捕捉到的異常  //throw new InputMismatchException(); 同上  }catch(ArithmeticException e){System.out.println("分母不能為0");thrownewArithmeticException("分母為0丟擲異常");//丟擲ArithmeticException異常  }catch(Exception e){//Exception是所有異常的父類  System.out.println("發生了其他異常");}finally{//不管是否出現異常,finally一定會被執行  System.out.println("程式結束");}}}

程式碼例子:(throws)

publicclassThrows{int a=1;int b=0;publicvoid out()throwsArithmeticException{//宣告可能要丟擲的異常,可以有多個異常,逗號隔開try{//監聽程式碼塊int sum=a/b;System.out.println(sum);}catch(ArithmeticException e){System.out.println("分母不能為0");}finally{//不管是否出現異常,finally一定會被執行System.out.println("程式結束");}}publicstaticvoid main(String[] args){Throws t=newThrows();
			t.out();//呼叫方法thrownewArithmeticException("分母為0丟擲異常");//由呼叫的方法決定是否要丟擲異常/*
			 * 第二種丟擲方式
			 *///			ArithmeticException a=new ArithmeticException("分母為0丟擲異常");//			throw a;}}