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


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


          網站導航:
           
          主站蜘蛛池模板: 正定县| 将乐县| 石嘴山市| 文山县| 会昌县| 兴隆县| 哈巴河县| 永仁县| 平罗县| 江山市| 周宁县| 宁乡县| 酒泉市| 英吉沙县| 盖州市| 淮安市| 西贡区| 兴仁县| 青神县| 新巴尔虎左旗| 扬州市| 湟中县| 恩平市| 襄汾县| 东乡| 江北区| 大港区| 鹿邑县| 扎兰屯市| 开远市| 东港市| 崇阳县| 康定县| 金秀| 铁岭市| 南丰县| 青州市| 盈江县| 富平县| 苗栗县| 岫岩|