標籤:style class blog code http ext
一、構建一個強型別異常來表示當前問題的獨特細節效果會更好。
假定要構建一個名為CarIsDeadException的自訂異常來表示加速註定要損壞的汽車的錯誤。
1.建立一個派生自System.Exception/System.ApplicationException的新類(按照約定,所有的一場類均應以“Exception”尾碼結束,這是.NET的最佳實務)。
1 namespace CustomException 2 { 3 public class CarIsDeadException : ApplicationException 4 { 5 private string messageDetails = String.Empty; 6 public DateTime ErrorTimeStamp { get; set; } 7 public string CauseOfError { get; set; } 8 9 public CarIsDeadException() { }10 11 public CarIsDeadException(string message, string cause, DateTime time)12 {13 messageDetails = message;14 CauseOfError = cause;15 ErrorTimeStamp = time;16 }17 18 //重寫Exception.Message屬性19 public override string Message20 {21 get22 {23 return string.Format("Car Error Message: {0}", messageDetails);24 }25 }26 }27 }
2.引發異常
從Accelerate()引發異常很直接,只需分配、配置和引發一個CarIsException類型,而不是通過System.Exception異常。
1 public void Accelerate(int delta)2 {3 ...... 4 5 CarIsDeadException ex = new CarIsDeadException(string.Format("{0} has overheated!", PetName), "You have a lead foot", DateTime.Now);6 ex.HelpLink = "http://www.CarsRus.com"; 7 throw ex;8 ......9 }
3.捕獲異常
1 namespace CustomException 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Car myCar = new Car("Rusty", 90); 8 9 try10 {11 myCar.Accelerate(50);12 }13 catch (CarIsDeadException e)14 {15 Console.WriteLine(e.Message);16 Console.WriteLine(e.ErrorTimeStamp);17 Console.WriteLine(e.CauseOfError);18 }19 }20 }21 }
通常情況下,僅需在出現錯誤的類與該錯誤關係緊密時才需要建立自訂異常(例如,一個自訂檔案類引發許多檔案相關的錯誤,一個Car類引發許多汽車相關的錯誤,一個Data Access Objects引發關於特定資料庫表的錯誤)。這樣我們就能使調用者逐個地處理眾多的異常。
二、改進
為了配置自訂錯誤資訊,當前的CarIsDeadException類重寫了System.Exception.Message屬性,並提供兩個自訂屬性來說明其他資料。
事實上,不要重寫Message虛屬性,而只需要將傳入的資訊按以下方式傳遞給父物件的建構函式:
1 namespace CustomException 2 { 3 public class CarIsDeadException : ApplicationException 4 { 5 public DateTime ErrorTimeStamp { get; set; } 6 public string CauseOfError { get; set; } 7 8 public CarIsDeadException() { } 9 10 //將資訊傳遞給父類物件建構函數11 public CarIsDeadException(string message, string cause, DateTime time)12 :base(message)13 {14 CauseOfError = cause;15 ErrorTimeStamp = time;16 }17 }18 }
很多情況下,自訂異常類的作用並不是提供繼承基類之外附加的功能,而是提供明確標識錯誤種類的強命名類型,因此客戶會為不同類型的異常提供不同的處理常式了邏輯。
三、構建一個嚴謹規範的自訂異常類
1.繼承自Exception/ApplicationException類;
2.有[System.Serializable]特殊標記;
3.定義一個預設的建構函式;
4.定義一個設定繼承的Message屬性的建構函式;
5.定義一個處理“內部異常”的建構函式;
6.定義一個處理類型序列化的建構函式。
例:
1 [Serializable] 2 public class CarIsDeadException : ApplicationException 3 { 4 public CarIsDeadException() { } 5 public CarIsDeadException(string message) 6 :base(message) 7 { 8 9 }10 public CarIsDeadException(string message, System.Exception inner)11 :base(message ,inner)12 {13 14 }15 protected CarIsDeadException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)16 :base(info, context)17 {18 19 }20 ......21 }
Visual Studio提供了一個叫做“Exception”的程式碼片段模板,它能自動產生一個新的遵循.NET最佳實務的異常類。輸入“exc”並連按兩次Tab鍵來啟用代碼。