2012-12-28 29 views

回答

16

是的。只需創建一個從Exception繼承的類。

class YourException : Exception 
{ 
    public YourException(SpecialObject thethingYouWantIncluded) 
    { 
     ExtraObject = thethingYouWantIncluded; 
    } 

    public SpecialObject ExtraObject { get; private set; } 
} 

然後

throw new YourException(new SpecialObject()); 

catch (YourException ex) { /* do something with ex.ExtraObject here */ } 
6

當然可以,有點。

在C#中,所有例外都是類,它們是System.Exception的實例或從中派生的某個類。如果要製作自定義異常,則只需定義一個從Exception繼承的新類。

在這個自定義類,你可以添加任何額外的屬性,字段等要:

public class CustomException : Exception 
{ 
    public Object CustomThing { get; set; } 
} 

當你趕上這樣的異常轉換類型的變量CustomException,你將有機會獲得所有的您定義的自定義屬性,就像任何其他類一樣。

但是,你不能做的是改變Exception.Message是字符串的事實。您的自定義消息類將具有Message屬性,它將是string,並且您無法更改它。您需要定義一個包含所有相關信息的自定義字符串。您可以覆蓋Message屬性從您的自定義屬性返回信息,但它仍然需要一個字符串:

public class CustomException : Exception 
{ 
    public override string Message 
    { 
     get 
     { 
      if (this.CustomThing == null) 
      { 
       return base.Message; 
      } 
      else 
      { 
       return string.Format("Custom thing: {0}", this.CustomThing); 
      } 
     } 
    } 
} 
+0

+1提到:「但是,你不能做的是改變Exception.Message是一個字符串的事實。」 – hometoast

相關問題