1. 程式人生 > >關於java 異常捕捉 ( try catch finally ) 執行流程

關於java 異常捕捉 ( try catch finally ) 執行流程

java中使用try catch finally做異常處理的情形較為常見,關於執行具體不同情況下的執行流程,在另一篇帖子中看到,說明較為詳細,但例子沒看太懂,故用自己的程式碼做貼留念。

參考部落格

以下內容在‘假設方法需要返回值’的前提下,如沒有此前提,便沒有探究執行流程的必要。

主要程式碼(通過加註釋達到不同情況):

public class Hello {
    public static void main(String[] args){
        System.out.println(tryCatchTest());
    }
    public static
String tryCatchTest(){ try { int i = 1 / 0; //引發異常的語句 System.out.println("try 塊中語句被執行"); return "try 塊中語句 return"; } catch (Exception e){ System.out.println("catch 塊中語句被執行"); return "catch 塊中語句 return"; } finally
{ System.out.println("finally 塊中語句被執行"); return "finally 塊中語句 return"; } } }

情況種類(忽略catch語句)

  1. 如果沒有 finally 程式碼塊,整個方法在執行完 try 程式碼塊後返回相應的值來結束整個方法;
  2. 如果有 finally 程式碼塊,此時程式執行到 try 程式碼塊裡的 return 語句之時並不會立即執行 return,而是先去執行 finally 程式碼塊裡的程式碼,
    2.1 若 finally 程式碼塊裡沒有 return 或沒有能夠終止程式的程式碼,程式將在執行完 finally 程式碼塊程式碼之後再返回 try 程式碼塊執行 return 語句來結束整個方法;
    2.2 若 finally 程式碼塊裡有 return 或含有能夠終止程式的程式碼,方法將在執行完 finally 之後被結束,不再跳回 try 程式碼塊執行 return。

程式碼演示:

情況1

public class Hello {
    public static void main(String[] args){
        System.out.println(tryCatchTest());
    }
    public static String tryCatchTest(){
        try {
//            int i = 1 / 0;      //引發異常的語句
            System.out.println("try 塊中語句被執行");
            return "try 塊中語句 return";
        }
        catch (Exception e){
            System.out.println("catch 塊中語句被執行");
            return "catch 塊中語句 return";
        }
//        finally {
//            System.out.println("finally 塊中語句被執行");
//            return "finally 塊中語句 return";
//        }
    }
}

結果

try 塊中語句被執行
try 塊中語句 return

情況2.1

public class Hello {
    public static void main(String[] args){
        System.out.println(tryCatchTest());
    }
    public static String tryCatchTest(){
        try {
//            int i = 1 / 0;      //引發異常的語句
            System.out.println("try 塊中語句被執行");
            return "try 塊中語句 return";
        }
        catch (Exception e){
            System.out.println("catch 塊中語句被執行");
            return "catch 塊中語句 return";
        }
        finally {
            System.out.println("finally 塊中語句被執行");
//            return "finally 塊中語句 return";
        }
    }
}

結果

try 塊中語句被執行
finally 塊中語句被執行
try 塊中語句 return

情況2.2

public class Hello {
    public static void main(String[] args){
        System.out.println(tryCatchTest());
    }
    public static String tryCatchTest(){
        try {
//            int i = 1 / 0;      //引發異常的語句
            System.out.println("try 塊中語句被執行");
            return "try 塊中語句 return";
        }
        catch (Exception e){
            System.out.println("catch 塊中語句被執行");
            return "catch 塊中語句 return";
        }
        finally {
            System.out.println("finally 塊中語句被執行");
            return "finally 塊中語句 return";
        }
    }
}

結果

try 塊中語句被執行
finally 塊中語句被執行
finally 塊中語句 return

如果有catch塊,基本和上面情況相似,只不過是把catch塊續到try塊引發異常語句後面,finally的地位依舊。