Throwable下有兩種,一種是Error錯誤類,另一種是Exception異常類。
異常exception又分爲運行時異常和非運行時異常
常見的4中運行時異常
-
ClassCastException(類轉換異常)
-
IndexOutOfBoundsException(數組越界)
-
NullPointerException(空指針)
-
ArithmeticExceptio(除數爲0)
運行時異常是在運行中出現的,在編譯時是不會報錯的,當你throw一個運行時異常時,不在方法外添加throws編譯器也不會發生報錯。
Throw:手動拋出異常
Throws:用在方法後面聲明可能會拋出的異常
異常處理機制-try-catch-finally
如果異常出現,程序沒有將其處理,那麼程序就會中斷,於是用異常處理機制-try-catch-finally。
try{
//可能發生異常的代碼
}catch(){
//處理異常的代碼
}finally{
//無論是否發生異常都會執行的代碼,常用於程序資源的回收處理
}
-try-catch-finally中可以有多個catch也可以沒有catch,但try必須和catch或者finally搭配使用。
dasda
-
不要把所有的代碼都寫到try裏面,try裏面的代碼執行時,系統維護堆棧跟蹤信息,執行效率低
-
catch是捕捉異常的,順序執行,所有不要把父類異常放在子類異常的上面,否則報錯。如果catch裏沒有捕捉到當前的異常,那麼程序還是會中斷
-
finally裏的代碼,不管異常是否捕捉都一定會執行。例io流中的close()方法一般都放到finally裏進行,finally於return也是個坑點。
finally&&return
try {
System.out.println("try "+i);
return i;
}finally{
++i;
System.out.println("finally "+i);
}
}
System.out.println(test());
System.out.println(i);
System.out.println("-----------------");
finally 1
0
1
-----------------
try {
System.out.println("try "+i);
return i;
}finally{
++i;
System.out.println("finally "+i);
}
}
System.out.println(test());
System.out.println(i);
System.out.println("-----------------");
finally 1
1
1
-----------------
int c = 0;
try {
c = 5 / 0;
System.out.println(5 / 0);
return 0;
} catch (NullPointerException e) {
System.out.println("空指針異常");
} finally {
System.out.println("finally");
}
return c;
}
System.out.println(test02());
System.out.println("test02 over");
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.z.exception.Return1.test02(Return1.java:19)
at com.z.exception.Return1.main(Return1.java:35)
try {
System.out.println(5 / 0);
return 0;
} catch (NullPointerException e) {
} finally {
System.out.println("finally");
return 0;
}
}
System.out.println(test01());
System.out.println("test01 over");
System.out.println("---------------------");
0
test01 over
---------------------
要注意的是,當finally有return時:
-
它會覆蓋try,catch中的return,方法返回的都將是finally中的
-