文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>[转载] try catch finally return 的执行顺序

[转载] try catch finally return 的执行顺序

时间:2010-10-10  来源:天涯走狗

 

public class JVMTest {
        public static void main(String[] args) {
                System.out.println("aa:" + aa());
        }

        public static int aa() {
                int a = 1;
                int b = 10;
                try {
                        System.out.println("abc");
                        return a;
                } finally {
                        a = 2;
                        System.out.println("a:" + a);
                }
        }
}


运行结果为:
abc
a: 2
aa:1
由此可知:在try语句中,在执行return语句时,要返回的结果已经准备好了,就在此时,程序转到finally执行了。
在转去之前,try中先把要返回的结果存放到不同于a的局部变量中去,执行完finally之后,在从中取出返回结果,
因此,即使finally中对变量a进行了改变,但是不会影响返回结果。


但是,如果在finally子句中最后添加上return a会怎样呢?
执行结果如下:
Compiling 1 source file to E:\sun\InsideJVM\build\classes
E:\sun\InsideJVM\src\JVMTest.java:37: warning: finally clause cannot complete normally
}
1 warning
compile-single:
run-single:
abc
a: 2
aa:2

测试1:
 

public static int test1()
{
    int i = 1;
    try
    {
        return ++i;
    }
    finally
    {
        ++i;
        Console.WriteLine("finally:" + i);
    }
}

static void Main(string[] args)
{
    Console.WriteLine("Main:" + test1());
}

结果:
finally:3
Main:2

测试2:

public static int test2()
{
    int i = 1;
    try
    {
        throw new Exception();
    }
    catch
    {
        return ++i;
    }
    finally
    {
        ++i;
        Console.WriteLine("finally:" + i);
    }
}

static void Main(string[] args)
{
    Console.WriteLine("Main:" + test2());
}


结果:
finally:3
Main:2

测试3:

public static int test3()
{
    try{}
    finally
    {
        return 1;
    }
}

结果:
编译错误,控制不能离开 finally 子句主体。

结论:

1.不管出没出现异常,finally块中的语句都会执行;
2.当try或catch块中有return语句时,finally块中的语句仍会执行;
3.finally块中的语句是在return语句执行之后才执行的,即函数返回值是在finally块中语句执行前确定的;
4.finally块中不能包含return语句。

总结:finally在return前执行,在finally的操作,不会改变已经确定的return的值,

finally不能加return语句。出现异常,先找是否有处理器可以处理这个异常.再finally。

相关阅读 更多 +
排行榜 更多 +
无限Fps

无限Fps

飞行射击 下载
幸存者时间僵尸

幸存者时间僵尸

飞行射击 下载
金属兄弟Metal Brother

金属兄弟Metal Brother

冒险解谜 下载