您的位置:首页 > 其它

try...catch...finally中的执行顺序和return语句 总结

2011-11-14 21:41 531 查看
需要首先注意的几点:
1) try catch finally中的finally不管在什么情况之下都会执行,执行的时间是在程序return 之前.有一点例外

public class FinallyTest1 {

public static String returnString() {

String str;

try {

str = "This is try block.";

System.out.println(str);

System.exit(0);

}

catch(Exception e) {

System.out.println("This is
catch block.");

}

finally {

System.out.println("This is
finally block.");

}

return null;

}

}

结果是:
This is try block.
可见,这种情况下,finally还未被执行,程序就退出了。碰到这种情况,如果还想在程序退出之前执行一些代码,可以参见addShutdownHook这个函数。

2)finally块中的return会覆盖掉try或catch块中的return,如果finally中没有return语句,try里面有return,那么在执行try中的return语句之前会先去执行finally中的代码,再去执行try中的return语句
return优先级:
finally>catch>try

3)如果try中的return是个值类型,finally中的代码不会影响它,
如果try中的return是个引用类型,finally中的代码会影响它
public class TestClass2
{
public int value = 1;
}

public class TestClass1
{
public static void main(String[ ] args)
{
System.out.println( Func2().value);
}

public static TestClass2 Func2()
{
TestClass2 t = new TestClass2();

try
{
return t;
}
finally
{
t.value++;
}
}
}


这一次运行的结果并不是1,而是2。显然,运行Func2()返回的结果并不直接是return后面写的t,而是经过finally块执行后值发生变化的t。

参考:http://www.yidilei.com/?action=show&id=450

/article/7328755.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐