C#拾遗系列(8):异常
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();
??????? }
??? }
}
轉載于:https://www.cnblogs.com/cnblogsfans/archive/2008/06/19/1225260.html
總結
以上是生活随笔為你收集整理的C#拾遗系列(8):异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nutch中MapReduce的分析[z
- 下一篇: c# char unsigned_dll