C# 自訂異常類型(摘自CLR Via C# 3th Edition)

來源:互聯網
上載者:User

 

ExceptionArgs.cs:

//異常資訊基類<br /> [Serializable]<br /> public abstract class ExceptionArgs {</p><p> public virtual String Message {<br /> get {<br /> return String.Empty;<br /> }<br /> }<br /> }

泛型的異常類:

[Serializable]<br /> public sealed class Exception<TExceptionArgs>:Exception,System.Runtime.Serialization.ISerializable<br /> where TExceptionArgs:ExceptionArgs{<br /> private const String c_args = "Args";<br /> private readonly TExceptionArgs m_args;</p><p> public TExceptionArgs Args {<br /> get {<br /> return m_args;<br /> }<br /> }</p><p> public Exception(string message = null, Exception innerException = null)<br /> : this(null, message, innerException) { }</p><p> public Exception(TExceptionArgs args, String message = null, Exception innerException = null)<br /> : base(message, innerException) { m_args = args; }</p><p> //該構造器用於還原序列化,由於類是密封的,所以構造器是私人的<br /> //如果類不是密封的,這個構造器就應該是受保護的<br /> [SecurityPermission(SecurityAction.LinkDemand,Flags=SecurityPermissionFlag.SerializationFormatter)]<br /> private Exception(SerializationInfo info,StreamingContext context)<br /> :base(info,context){<br /> m_args = (TExceptionArgs)info.GetValue(c_args, typeof(TExceptionArgs));<br /> }</p><p> //這個方法用於序列化,由於實現了ISerializable介面,所以它是公用的(該方法為ISerializable中定義的方法)<br /> //在Exception類中已有實現,此類繼承了Exception,並重寫了該方法在Exception中的實現<br /> [SecurityPermission(SecurityAction.LinkDemand,Flags=SecurityPermissionFlag.SerializationFormatter)]<br /> public override void GetObjectData(SerializationInfo info, StreamingContext context) {<br /> info.AddValue(c_args, m_args);<br /> base.GetObjectData(info, context);<br /> }</p><p> public override string Message {<br /> get {<br /> String baseMsg = base.Message;<br /> return (m_args == null) ? base.Message : baseMsg + "(" + m_args.Message + ")";<br /> }<br /> }</p><p> public override bool Equals(object obj) {<br /> Exception<TExceptionArgs> other = obj as Exception<TExceptionArgs>;<br /> if (obj==null) {<br /> return false;<br /> }<br /> return Object.ReferenceEquals(m_args, other.m_args) && base.Equals(obj);<br /> }</p><p> public override int GetHashCode() {<br /> return base.GetHashCode();<br /> }<br /> }

註:C#只允許自訂的類繼承自系統異常類的基類:System.Exception,並且繼承自System.Exception類的所有異常類型,都必須是可被序列化的,這使得這些異常資訊得以穿越AppDomain(比如Remoting服務端異常有可能需要返回到遠程調用方,這時就不得不穿越AppDomain)或者寫入日誌/資料庫等。

 

定義一個磁碟滿的異常類:

//定義一個磁碟滿的異常類<br /> [Serializable]<br /> public sealed class DiskFullExceptionArgs:ExceptionArgs {<br /> //readonly:唯讀,動態常量,只能在構造器中被賦值<br /> private readonly String m_diskpath;</p><p> public DiskFullExceptionArgs(String diskpath) {<br /> m_diskpath = diskpath;<br /> }</p><p> public String DiskPath {<br /> get {<br /> return m_diskpath;<br /> }<br /> }</p><p> public override string Message {<br /> get {<br /> return (m_diskpath == null) ? base.Message : "DiskPath=" + m_diskpath;<br /> }<br /> }</p><p> }

 

如果沒有額外的資料要包含到類中,可以簡單地寫:

//定義一個磁碟滿的異常類<br /> [Serializable]<br /> public sealed class DiskFullExceptionArgs:ExceptionArgs { }

 

拋出/捕獲自訂異常:

public void TestException() {<br /> try {<br /> throw new Exception<DiskFullExceptionArgs>(<br /> new DiskFullExceptionArgs(@"C:/"), "The disk is full");<br /> }<br /> catch (Exception<DiskFullExceptionArgs> ex) {<br /> Console.WriteLine(ex.Message);<br /> }<br /> }

 

 

 

相關文章

聯繫我們

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