2016-09-29 70 views
0

我有一個擁有屬性的類。在此屬性中,我試圖驗證數據表不爲空。如果它爲空,則會生成一個異常。在引用者中引發異常

我的問題是如果我想在標籤控件中顯示錯誤消息,例如在調用類中如何捕獲該問題。

這裏是屬性:

public DataTable DtNotes 
    { 
     get 
     { 
      return _dtNotes; 
     } 
     set 
     { 
      _dtNotes = value; 
      if (_dtNotes != null) 
      { 
       _dtNotes.Columns.Remove("id"); 
       _dtNotes.DefaultView.Sort = "note_type ASC"; 
       _dtNotes.AcceptChanges(); 
      } 
      else 
      { 
       throw new ArgumentOutOfRangeException("value", "Null Datable"); 
      } 
     } 
    } 

我用這一個asp.net應用程序中。

+0

旁白:注意類的'存在ArgumentNullException' –

+0

我希望你重新拋出任何'ArgumentOutOfRangeException '你抓住的例外...... –

+0

@MthetheWWatson - 他爲什麼要這麼做?他唯一的要求是當異常發生時顯示一條消息。在這裏重新投擲聽起來不像是一個理想的結果。 –

回答

4

在調用類使用try-catch塊和catch塊顯示您的消息:

try 
{ 
    // use DtNotes here, throws an ex. 
} 
catch (ArgumentOutOfRangeException ex) 
{ 
    // display message here. 
} 
+0

謝謝,解決了它。 – Andyww

0
var myClass = new MyClass(); 
try { 
    myClass.DtNotes = null; //Null assignment throws exception 
} catch (ArgumentOutOfRangeException ex){ //Catch the exception 
    string message = ex.Message; //Retrieve the message 
    //You can display the message here 
}