標籤:style color rgs 建立 before static exe str public
這一篇部落格用例子講述一下異常的處理過程。
異常的執行過程一、執行個體一:return語句
public class ExceptionTest_1 { public static void main(String[] args) { int result = 0; try { System.out.println("before result"); result = 9 / 0; System.out.println("after result"); } catch (Exception e) { System.out.println("exception" + e.getMessage() + ", result: " + result); return; } finally { System.out.println("final execute, " + result); } System.out.println("out of try statement, " + result); }}
執行的結果如下:
before resultexception/ by zero, result: 0final execute, 0
將上述代碼result = 9 / 0改為 result = 9 / 2;也就是不產生異常,執行的結果如下:
before resultafter resultfinal execute, 4out of try statement, 4
二、執行個體二:try裡面有try語句
public class ExceptionTest_2 { public static void main(String[] args) { try { if (1 + 2 > 2) { throw new FileNotFoundException(); } try { throw new FileNotFoundException(); } catch (FileNotFoundException e) { System.out.println("world hello"); } } catch (Exception e) { System.out.println("hello world"); } finally { System.out.println("final action"); } }}
執行的結果如下:
hello worldfinal action
如果將if(1 + 2 > 2)改變if(1 + 2 > 4),也就是try塊裡面沒有拋出異常。執行的結果如下:
world hellofinal action
簡短的異常說明:
當拋出異常後,會發生以下的事情。1、用new在堆上建立異常對象,當前的執行路徑被終止,並從當前環境中彈出異常對象的引用。2、異常處理機制接管程式,並尋找一個恰當的地方繼續執行程式。3、如果有定義了final,那麼會執行final塊的代碼。
友情連結
- 詳細的異常說明:http://blog.csdn.net/hguisu/article/details/6155636
java基礎---->Java中異常的使用(二)