try-catch-finally,trycatch

來源:互聯網
上載者:User

try-catch-finally,trycatch

通過中間代碼窺探try-catch-finally本質:

class Program    {        static void Main(string[] args)        {            Program p = new Program();            Console.WriteLine(p.Test1());            //Console.WriteLine(p.Test2());            Console.Read();        }        //結果為:3        private TestClass Test1()        {            TestClass tc = new TestClass();            try            {                tc.testVar = 2;                return tc;            }            catch (Exception)            {                throw;            }            finally            {                tc.testVar = 3;            }        }        //結果為:2        private int Test2()        {            int test = 1;            try            {                test = 2;                return test;            }            catch (Exception)            {                throw;            }            finally            {                test = 3;            }        }    }    class TestClass    {        public int testVar = 111;        public override string ToString()        {            return testVar.ToString();        }    }


調用方法Test1,中間代碼賦予本地變數的僅是一個引用,所以finally的操作是有影響的,其中間代碼為:



調用方法Test2,try中return時,已經將返回值儲存在中間代碼的本地變數中,而不再是源碼中變數test,所以finally的操作是無效的。其中間代碼為:



java中try-catch-finally塊的代碼運行順序是怎的?

繼續運行
try{
拋異常的語句
}catch(捕獲異常){
列印堆棧
}
finally{
一般是釋放資源(例如你在try 裡開啟了一個檔案,出了異常,沒有關閉它,finally裡面寫的就像這種)

finally裡面的語句不管catch執行不執行都會走的
}
下面的語句正常運行,不影響
 
程式中使用try-catch-finally語句結構處理異常的方法

從try程式塊中得到異常,然後再catch塊中做處理(一般是拋出,資料復原,寫日誌等等),在finally塊中的程式是最後執行的(不論是否前面的程式拋出異常)。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.