一、關鍵技術點:
1、關鍵字finally用在try和catch語句之後,表示無論是否發生異常,都會執行finally塊中的代碼
2、一般情況下,先執行try塊,如果有異常再執行catch塊,最後才執行finally塊,除非try塊或者catch塊中有跳轉語句,如:return,那麼在執行跳轉語句之前,finally塊中的代碼被執行。是以,finally塊中的代碼一定會被執行。
3、由于finally塊中的代碼肯定會執行,是以常常将關閉資源(如關閉檔案、資料庫連接配接等)的語句放在fianlly中。
4、不要在finally塊中用跳轉語句,如return等,因為這會使得try和catch塊中的跳轉語句失效
二、示範執行個體
package book.exception;
public class Finally ... {
public static double getSqrt(String nStr) throws MyFirstException, MySecondException ...{
if (nStr == null) ...{
throw new MyFirstException("輸入的字元串不能為空!");
}
double n = 0;
try ...{
n = Double.parseDouble(nStr);
} catch (NumberFormatException e) ...{
throw new MyFirstException("輸入的字元串必須能夠轉化成數字!");
}
if (n < 0) ...{
throw new MySecondException("輸入的字元串轉化成的數字必須大于等于0!");
}
return Math.sqrt(n);
}
public static double testFinallyA(String nStr) ...{
try ...{
System.out.println("Try block! ");
return getSqrt(nStr);
} catch (MyFirstException e1) ...{
System.out.println("Catch MyFirstException block!");
System.out.println("Exception: " + e1.getMessage());
return -1;
} catch (MySecondException e2) ...{
System.out.println("Catch MySecondException block!");
System.out.println("Exception: " + e2.getMessage());
return -2;
} finally ...{
System.out.println("Finally block!");
}
}
public static double testFinallyB(String nStr) ...{
try ...{
System.out.println("Try block! ");
return getSqrt(nStr);
} catch (MyFirstException e1) ...{
System.out.println("Catch MyFirstException block!");
System.out.println("Exception: " + e1.getMessage());
return -1;
} catch (MySecondException e2) ...{
System.out.println("Catch MySecondException block!");
System.out.println("Exception: " + e2.getMessage());
return -2;
} finally ...{
System.out.println("Finally block!");
//增加一行,傳回一個值
return 0;
}
}
public static void main(String[] args) ...{
System.out.println("使用testFinallyA方法:");
System.out.println("沒有發生異常是輸出:");
System.out.println("result: " + Finally.testFinallyA("123.4"));
System.out.println("發生異常時輸出:");
System.out.println("result: " + Finally.testFinallyA("dfdg"));
System.out.println();
System.out.println("使用testFinallyB方法:");
System.out.println("沒有發生異常是輸出:");
System.out.println("result: " + Finally.testFinallyB("123.4"));
System.out.println("發生異常時輸出:");
System.out.println("result: " + Finally.testFinallyB("dfdg"));
}
}
程式輸出:
使用testFinallyA方法:
沒有發生異常是輸出:
Try block !
Finally block !
result: 11.108555261599053
發生異常時輸出:
Try block !
Catch MyFirstException block !
Exception: 輸入的字元串必須能夠轉化成數字!
Finally block !
result: - 1.0
使用testFinallyB方法:
沒有發生異常是輸出:
Try block !
Finally block !
result: 0.0
發生異常時輸出:
Try block !
Catch MyFirstException block !
Exception: 輸入的字元串必須能夠轉化成數字!
Finally block !
result: 0.0
源碼分析:
着重看testFinallyB方法的輸出,在testFinallyB方法中的finally塊總使用了跳轉語句"return 0"。因為finally塊的語句在try和catch中的跳轉語句執行之前被執行,在執行finally語句中的跳轉語句後,将無法執行try和catch中的跳轉語句。是以該方法總是傳回0.