JAVA中的異常如何處理?

try catch

基本用法

try{
    //有可能出現異常的語句
}catch(Exception e){//異常的類型 和接受對象

}finally {
    //異常的出口,最後執行且一定被執行
}

注:可以不寫finally語句;

示例

try{
    int[] array = new int[9];
    array[100] = 100;//下標越界

}catch(ArrayIndexOutOfBoundsException a){//異常的類型 和接受對象
    System.out.println("下標越界異常");
    a.printStackTrace();//輸出異常信息

}finally {
    System.out.println("finally.請重寫數組下標");
    //異常的出口,最後執行且一定被執行
}

運行結果

下標越界異常
java.lang.ArrayIndexOutOfBoundsException: 100
 at com.bit.demo1.Test10.main(Test10.java:35)
finally.請重寫數組下標

防禦式編程

1.LBYL方式:運行前檢查
2.EAFP方式:使用try catch等方法處理可能發生異常的語句;
EAFP式編程的好處是當程序運行出現錯誤時,可以同時進行處理操作,保證程序繼續運行;

finally的注意事項

代碼:

try{
    int[] array = new int[9];
    array[100] = 100;
    return 10;

}catch(ArrayIndexOutOfBoundsException a){
    return 20;

}finally {
    return 30;
}

運行結果爲30:因爲finally是最後執行的語句,且一定執行,它將覆蓋原來的返回值;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章