java中的try与finally

View Code
 1 package exercise;
2 /**
3 * 基本类型测试try,finally
4 * @author Administrator
5 *
6 */
7 public class TestReturnAndFinally {
8 public static void main(String[] args) {
9 // TODO Auto-generated method stub
10 System.out.println(new TestReturnAndFinally().test());;
11 }
12
13 static int test() {
14 int x = 1;
15 try {
16 return x;
17 }
18 finally {
19 ++x;
20 }
21 }
22 }

结果:1

View Code
 1 package exercise;
2 /**
3 * 引用类型测试try,finally
4 * @author Administrator
5 *
6 */
7 public class TestReturnAndFinally3 {
8 public static void main(String[] args) {
9 // TODO Auto-generated method stub
10 System.out.println(new TestReturnAndFinally3().test());;
11 }
12
13 static StringBuffer test() {
14 StringBuffer a = new StringBuffer("init");
15
16 try {
17 a.append(" try");
18 return a;
19 }
20 finally {
21 a.append(" finally");
22 }
23 }
24 }

结果:init try finally

 1 package exercise;
2 /**
3 * 引用类型测试try,finally
4 * @author Administrator
5 *
6 */
7 public class TestReturnAndFinally3 {
8 public static void main(String[] args) {
9 // TODO Auto-generated method stub
10 System.out.println(new TestReturnAndFinally3().test());;
11 }
12
13 static String test() {
14 String a = new String("init");
15
16 try {
17 a = new String("try");
18 return a;
19 }
20 finally {
21 a = new String("finally");
22 }
23 }
24 结果:t


View Code
 1 package exercise;
2
3 /**
4 * 普通类
5 * @author Administrator
6 *
7 */
8 public class Quote {
9 public int a = 1;
10 }
11
12
13
14
15 package exercise;
16 /**
17 * 引用类型中的基本类型测试try,finally
18 * @author Administrator
19 *
20 */
21 public class TestReturnAndFinally2 {
22 public static void main(String[] args) {
23 // TODO Auto-generated method stub
24 System.out.println(new TestReturnAndFinally2().test().a);;
25 }
26
27 static Quote test() {
28 Quote q = new Quote();
29
30 try {
31 return q;
32 }
33 finally {
34 q.a++;
35 }
36 }
37 }

结果:2

 

结论:任何调用try 或者catch中的return语句之前,都会先执行finally语句,当然前提是finally存在。如果finally中有return语句,那么程序就return了,所以finally中的return是一定会被return的,编译器把finally中的return实现为一个warning。

posted on 2012-04-07 16:35  lovebeauty  阅读(1039)  评论(0编辑  收藏  举报

导航