try-catch中finally执行的时机

来源:互联网 发布:c语言 新建文件追加 编辑:程序博客网 时间:2024/05/29 19:02

也许你的答案是在return之前,但往更细地说,我的答案是在return中间执行,请看下面程序代码的运行结果:

public  class Test {    public static void main(String[] args) {        System.out.println(new Test().test());    }    static int test() {        int x = 1;        try {            return x;        } finally {            ++x;        }    }}

———执行结果 ———
1

为什么呢?主函数调用子函数并得到结果的过程,好比主函数准备一个空罐子,当子函数要返回结果时,先把结果放在罐子里,然后再将程序逻辑返回到主函数。所谓返回,就是子函数说,我不运行了,你主函数继续运行吧,这没什么结果可言,结果是在说这话之前放进罐子里的。

public class  smallT {    public static void  main(String args[]) {        smallT t = new smallT();        int b  = t.get();        System.out.println(b);    }    public int  get() {        try {            return 1 ;        } finally {            return 2 ;        }    }}

返回结果是 ———-
2

我可以通过下面一个例子程序来帮助我解释这个答案,从下面例子的运行结果中可以发现,try中的return语句调用的函数先于finally中调用的函数执行,也就是说return语句先执行,finally语句后执行,所以,返回的结果是2。return并不是让函数马上返回,而是return语句执行后,将把返回结果放置进函数栈中,此时函数并不是马上返回,它要执行finally语句后才真正开始返回。

用下面的程序来帮助分析:

public  class Test {        public static void main(String[] args) {        System.out.println(new Test().test());    }    int test() {        try {            return func1();        } finally {            return func2();        }    }    int func1() {        System.out.println("func1");        return 1;    }    int func2() {        System.out.println("func2");        return 2;    }}

执行结果———–
func1
func2
2

**结论:finally中的代码比return 和break语句后执行。**
0 0
原创粉丝点击