C#拾遺系列(8):異常

來源:互聯網
上載者:User

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace NetTest

{

    public class TestException

    {

        public void TestThrow()

        {

            //try 塊必須與 catch 或 finally 塊一起使用,並且可以包括多個 catch 塊

            try

            {

                CustomException ex = new CustomException("test custom exception");

                ex.ModuleName = "Front-End";

                throw ex;

            }

            /*

            多個 catch 塊可以串聯在一起。多個 catch 塊的計算順序是從頂部到底部

            但是,對於所引發的每個異常,都只執行一個 catch 塊。

            與所引發異常的準確類型或其基類最為匹配的第一個 catch 塊將被執行。

            如果沒有任何 catch 塊指定匹配的異常篩選器,則將執行不帶篩選器的 catch 塊(如果有的話)。

            需要將帶有最具體的(即派生程度最高的)異常類的 catch 塊放在最前面

           */

            catch (CustomException ex)

            {

                System.Console.Out.WriteLine(ex.Message + "Module is:" + ex.ModuleName);

                System.Console.Out.WriteLine("------------------------------");

                System.Console.Out.WriteLine(ex.ToString());

            }

            catch (Exception ex)

            {

                System.Console.Out.WriteLine(ex.Message);

            }

 

            //Finally 塊可讓程式員清理中止的 try 塊可能留下的任何不明確狀態,

            //或釋放任何外部資源(形控制代碼、資料庫連接或檔案流)

            //而不用等待運行庫中的記憶體回收行程來終結這些對象,finally塊任何情況都執行

            finally

            {

                // Code to execute after try (and possibly catch) here

                System.Console.Out.WriteLine("test complete");

            }

        }

    }

 

    //自訂的異常

    [Serializable]

    class CustomException : Exception

    {

 

        public CustomException(string message):base(message)

        {           

        }

        public string ModuleName { get; set; }

 

        public override string ToString()

        {

            return base.ToString() + this.ModuleName.ToString();

        }

    }

}

相關文章

聯繫我們

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