C#3.0學習筆記(3)例外處理常式try catch語句

來源:互聯網
上載者:User

一,  什麼叫異常?

       異常就是程式運行時的錯誤,它違反了一個系統約束或應用程式約束,或出    現了在正常操作時未預料的情形。如用0去除一個數時就會發生異常。

二,  try…catch…finally…語句的結構?

       未例:

       try

       {

              Statement;

       }

       catch(…)

       {

              Statement;

       }

       finally

       {

              Statement;

       }

1、 try塊包括正被異常保護的代碼。

2、 catch塊是處理異常的代碼塊,也稱例外處理常式。

3、 finally塊是在所有情況下無論如何都要執行的代碼,無論有沒有異常發生。

三,  綜合樣本:

       namespace try_catch

{

    class Program

    {

        static voidMain(string[] args)

        {

            MyClass mc = new MyClass();

            try

            {

                mc.A();

            }

            catch (DivideByZeroException)

            {

                Console.WriteLine("catch clause inMain()");

            }

            finally

            {

                Console.WriteLine("finally clause inMain()");

            }

            Console.WriteLine("After try statement inMain.");

            Console.WriteLine("   --keep running!");

        }

    }

    class MyClass

    {

        public void A()

        {

            try

            {

                B();

            }

            catch (System.NullReferenceException)

            {

                Console.WriteLine("catch clause in A()");

            }

            finally

            {

                Console.WriteLine("finally clause in A()");

            }

        }

        protected void B()

        {

            int x = 10, y = 0;

            try

            {

                x /= y;

            }

            catch (System.IndexOutOfRangeException)

            {

                Console.WriteLine("catch clause in B()");

            }

            finally

            {

                Console.WriteLine("finally clause in B()");

            }

        }

    }

}

程式輸出結果為:

finally clause in B()

finally clause in A()

catch clause inMain()

finally clause inMain()

After try statement inMain.

   --keep running.

相關文章

聯繫我們

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