Java異常發生時程序的執行順序
一些基礎知識:
1.try代碼段包含可能產生例外的代碼;
2.try代碼段后跟有一個或多個代碼段;
3.每個catch代碼段聲明其能處理的一種特定的異常并提供處理的方法;
4.當異常發生時,程序會終止當前的流程,根據獲取異常的類型去執行相應的catch代碼段,有多個符合條件的catch時,只執行第一個;
5.finally段的代碼無論是否發生異常都會執行。
6.在一個try語句塊中,基類異常的捕獲語句不可以寫在子類異常捕獲語句的上面。
看一個例子:
/** * @author Lansine * */ public class T1 { /** * @param args */ public static void main(String[] args) { String s = "1"; try { s = "2"; System.out.println(s); if (s == "2") throw new Exception("h"); } catch (Exception e) { s = "3"; System.out.println(s); } finally { s = "4"; System.out.println(s); } s = "5"; System.out.println(s); } } |
輸出的結果是2,3,4,5 (這里的逗號只用于顯示)。上述語句非常清楚,但是在上述結構中加上return,就變得有些復雜了,如
/** * @author Lansine * */ public class T2 { /** * @param args */ public static void main(String[] args) { String s = "1"; try { s = "2"; System.out.println(s); return; } catch (Exception e) { s = "3"; System.out.println(s); } finally { s = "4"; System.out.println(s); } s = "5"; System.out.println(s); } } |
輸出的結果是2,4也就是說在try結構中,雖然使用了return語句強制函數返回,不再往下執行,但實現上finally中的還是執行了。但除了finally外的其它語句不再被執行。
一個更流行的例子是:
import java.io.*; /** * @author Lansine * */ public class Mine { public static void main(String argv[]){ Mine m = new Mine(); try { System.out.println(m.amethod()); } catch (Exception e) { // TODO 自動生成 catch 塊 //e.printStackTrace(); System.out.println("我知道了"); } System.out.println("finished"); } public int amethod()throws Exception { try { FileInputStream dis = new FileInputStream("Hello.txt"); // 1,拋出異常 System.out.println("異常發生之后"); } catch (Exception ex) { System.out.println("No such file found"); // 2.catch捕捉異常,并執行 //throw new Exception("上面處理"); return -1; // 4,return 返回 } finally { System.out.println("Doing finally"); // 3.finally一定會執行,在return之前。 } System.out.println("在代碼后面"); return 0; } } |
結果是:
No such file found
Doing finally
-1
finished
如果在catch塊中拋出異常,則結果為:
No such file found
Doing finally
我知道了
finished
注意:如果異常往上拋直到main函數還沒有被catch處理的話,程序將被異常終止。
posted on 2014-07-02 16:38 順其自然EVO 閱讀(350) 評論(0) 編輯 收藏 所屬分類: 測試學習專欄