finally知多少
先来看一下以下的代码,猜猜他们会是什么样的结果:1 public class FinallyIssue {
2 public static void main(String[] args) {
3 System.out.println( " finallyReturnTest : " );
4 System.out.println( " return value : " + finallyReturnTest( 1 ));
5 System.out.println( " return value : " + finallyReturnTest( - 1 ));
6
7 System.out.println( " finallyBreakTest : " );
8 System.out.println( " return value : " + finallyBreakTest( true ));
9 System.out.println( " return value : " + finallyBreakTest( false ));
10
11 System.out.println( " valueChangeInFinallyTest : " );
12 System.out.println( " return value : " + valueChangeInFinallyTest());
13
14 System.out.println( " valueChangeReturnInFinallyTest : " );
15 System.out.println( " return value : " + valueChangeReturnInFinallyTest());
16
17 System.out.println( " refValueChangeInFinallyTest : " );
18 System.out.println( " return name : " + refValueChangeInFinallyTest().name);
19 }
20
21 private static boolean finallyReturnTest( int value) {
22 try {
23 if (value > 0 ) {
24 return true ;
25 } else {
26 return false ;
27 }
28 } finally {
29 return false ;
30 }
31 }
32
33 private static boolean finallyBreakTest( boolean value) {
34 while (value) {
35 try {
36 return true ;
37 } finally {
38 break ;
39 }
40 }
41 return false ;
42 }
43
44 private static int valueChangeInFinallyTest() {
45 int i = 10 ;
46 int j = 1 ;
47 try {
48 i = 100 ;
49 j = 2 ;
50 System.out.println( " try : i = " + i);
51 System.out.println( " try : j = " + j);
52 return i;
53 } catch (Exception e) {
54 e.printStackTrace();
55 } finally {
56 i = 1000 ;
57 j = 3 ;
58 System.out.println( " finally : i = " + i);
59 System.out.println( " finally : j = " + j);
60 }
61
62 return i;
63 }
64
65 private static int valueChangeReturnInFinallyTest() {
66 int i = 10 ;
67 int j = 1 ;
68 try {
69 i = 100 ;
70 j = 2 ;
71 System.out.println( " try : i = " + i);
72 System.out.println( " try : j = " + j);
73 return i;
74 } catch (Exception e) {
75 e.printStackTrace();
76 } finally {
77 i = 1000 ;
78  
补充:软件开发 , Java ,