java中的try與finally

來源:互聯網
上載者:User
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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.