1. 程式人生 > 其它 >Java的try/catch/finally中使用return詳解

Java的try/catch/finally中使用return詳解

技術標籤:Java

finally是無論如何都要執行的,除非在try/catch的語句塊中使用的System.exit()

為了弄清楚Java中try/catch/finally中使用return語句的跳轉,使用下面示例:

1. 首先在try中使用returnfinally中不使用return

public class App {
    public static void main(String[] args) throws Exception {
        App app = new App();
        String res = app.test();
        System.
out.println(res); } public String test() { try { System.out.println("正在執行 try"); return new String("返回 try"); } catch (Throwable throwable) { System.out.println("異常"); return new String("catch"
); } finally { System.out.println("正在執行 finally"); // return new String("返回 finally"); } } }
執行結果

在這裡插入圖片描述
由此可見執行順序:try中語句——>finally中語句——>try中return語句

2. 在try中使用returnfinally中也使用return

public class App {
    public static void main(String[
] args) throws Exception { App app = new App(); String res = app.test(); System.out.println(res); } public String test() { try { System.out.println("正在執行 try"); return new String("返回 try"); } catch (Throwable throwable) { System.out.println("異常"); return new String("catch"); } finally { System.out.println("正在執行 finally"); return new String("返回 finally"); } } }
執行結果

在這裡插入圖片描述
執行順序:try中語句——>finally中語句——>finally中的return

3. 在catch中使用return

public class App {
    public static void main(String[] args) throws Exception {
        App app = new App();
        String res = app.test();
        System.out.println(res);
    }

    public String test() {
        try {
            System.out.println("正在執行  try");
            throw new Throwable("Some error");
        } catch (Throwable throwable) {
            System.out.println("異常");
            return new String("catch");
        } finally {
            System.out.println("正在執行  finally");
            return new String("返回  finally");
        }
    }
}

執行順序和前面類似:try中語句——>catch中語句——>finally中語句——>finally中return

綜上所述

在執行完trycatch語句中後,都會執行finally中的語句,此時,如果finally中有return就直接從這裡跳出。如果沒有的話,就從try或者catch中的return中返回。