posts - 110, comments - 101, trackbacks - 0, articles - 7
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

try catch finally return 执行顺序

Posted on 2011-11-10 21:20 云云 阅读(516) 评论(1)  编辑  收藏

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.当trycatch块中有return语句时,finally块中的语句仍会执行;
3.finally块中的语句是在return语句执行之后才执行的,即函数返回值是在finally块中语句执行前确定的;
4.finally块中不能包含return语句。

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

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


只有注册用户登录后才能发表评论。


网站导航: