1. 程式人生 > >java編譯時異常和執行時異常

java編譯時異常和執行時異常

一 什麼是編譯時異常,什麼是執行時異常

執行時異常可以通過改變程式避免這種情況發生,比如,除數為0異常,可以先判斷除數是否是0,如果是0,則結束此程式。從繼承上來看,只要是繼承RunTimeException類的,都是執行時異常,其它為編譯時異常。

二編譯時異常和執行時異常的區別

使用丟擲處理方式處理異常時,對於編譯時異常,當函式內部有異常丟擲,該函式必須宣告,呼叫者也必須處理執行時異常則不一定要宣告,呼叫者也不必處理
ArithmeticException執行時異常
  1. publicclass Test {  
  2.     publicstaticint a=0;  
  3.     publicstatic
    void main(String[] args){  
  4.         // TODO Auto-generated method stub
  5.           a = test(4,0);  
  6.     }  
  7.     publicstaticint test(int a,int b){  
  8.         if(b==0){  
  9.           thrownew ArithmeticException();  
  10.         }  
  11.         return a/b;  
  12.     }  
  13. }  
列印結果: Exception in thread "main" java.lang.ArithmeticException
at testexception.Test.test(Test.java:11)
at testexception.Test.main(Test.java:7)
從上面程式碼中可以看出,執行時異常可以不需宣告異常 下面是編譯時異常,TimeOutException,超時連線異常,模擬當i大於10時,即超過10秒,丟擲連線超時異常。
  1. package testexception;  
  2. import java.util.concurrent.TimeoutException;  
  3. publicclass Test {  
  4.     publicstaticvoid main(String[] args)throws TimeoutException{  
  5.         // TODO Auto-generated method stub
  6.          test(11
    );  
  7.     }  
  8.     publicstaticvoid test(int i) throws TimeoutException{  
  9.         if(i>10)  
  10.           thrownew TimeoutException();  
  11.         System.out.println("連線沒有超時");  
  12.     }  
  13. }  

列印結果:

Exception in thread "main" java.util.concurrent.TimeoutException
at testexception.Test.test(Test.java:12)
at testexception.Test.main(Test.java:8)
從上面可以看出,編譯時異常必須在函式中宣告,呼叫者也必須在函式中處理.