java編譯時異常和執行時異常
阿新 • • 發佈:2019-01-30
一 什麼是編譯時異常,什麼是執行時異常
執行時異常可以通過改變程式避免這種情況發生,比如,除數為0異常,可以先判斷除數是否是0,如果是0,則結束此程式。從繼承上來看,只要是繼承RunTimeException類的,都是執行時異常,其它為編譯時異常。
二編譯時異常和執行時異常的區別
使用丟擲處理方式處理異常時,對於編譯時異常,當函式內部有異常丟擲,該函式必須宣告,呼叫者也必須處理,執行時異常則不一定要宣告,呼叫者也不必處理;ArithmeticException執行時異常
- publicclass Test {
- publicstaticint a=0;
- publicstatic
- // TODO Auto-generated method stub
- a = test(4,0);
- }
- publicstaticint test(int a,int b){
- if(b==0){
- thrownew ArithmeticException();
- }
- return a/b;
- }
- }
at testexception.Test.test(Test.java:11)
at testexception.Test.main(Test.java:7)
- package testexception;
- import java.util.concurrent.TimeoutException;
- publicclass Test {
- publicstaticvoid main(String[] args)throws TimeoutException{
- // TODO Auto-generated method stub
-
test(11
- }
- publicstaticvoid test(int i) throws TimeoutException{
- if(i>10)
- thrownew TimeoutException();
- System.out.println("連線沒有超時");
- }
- }
列印結果:
Exception in thread "main" java.util.concurrent.TimeoutExceptionat testexception.Test.test(Test.java:12)
at testexception.Test.main(Test.java:8)
從上面可以看出,編譯時異常必須在函式中宣告,呼叫者也必須在函式中處理.