posts - 110, comments - 101, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          try catch finally return 執行順序

          Posted on 2011-11-10 21:20 云云 閱讀(528) 評論(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


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 苍南县| 东源县| 大石桥市| 天门市| 东海县| 延安市| 横峰县| 元江| 奈曼旗| 龙口市| 平武县| 陆川县| 洪雅县| 乐业县| 大悟县| 濮阳县| 泰顺县| 巴彦淖尔市| 永兴县| 邵阳市| 饶河县| 平凉市| 兴文县| 张家口市| 霍城县| 九寨沟县| 灵宝市| 民丰县| 安陆市| 西乌| 沅江市| 中西区| 孝昌县| 敦化市| 福贡县| 永年县| 磐石市| 本溪市| 建始县| 昌邑市| 巴南区|