面试题:try-catch-finally,try里有return,finally还执行么?

525 阅读1分钟

Q:try-catch-finally,try里有return,finally还执行么?

代码

public class TryDemo {
    public static void main(String[] args) {
        int result = test();
        System.out.println("result: " + result);
    }

    private static int test() {
        int result = 0;
        int a = 0;
        int b = 10;
        try {
            result = a + b;
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(" finally 里的函数....");
        }
        result = 20;
        return result;
    }
}

看执行结果

Screen Shot 2022-02-07 at 16.23.40.png

结论

  • try 里面return了 ,finally里面的代码,还是一定会走的!