2012-08-22 179 views
2

我有一句臺詞: string[] cPathDirectories = Directory.GetDirectories(Properties.Settings.Default.customerFolderDirectory);自定義錯誤

,將拋出錯誤「路徑不是法律形式」,如果用戶沒有指定的搜索路徑(此設置保存爲String.Empty在這一點上)。我想拋出這個錯誤,說:「嘿,你白癡,進入應用程序設置,並指定一個有效的路徑」,而不是。有沒有辦法做到這一點,而不是:

...catch (SystemException ex) 
{ 
    if(ex.Message == "Path is not of legal form.") 
     { 
      MessageBox.Show("Hey you idiot, go into the application settings and specify a valid path","Error"); 
     } 
     else 
     { 
      MessageBox.Show(ex.Message,"Error"); 
     } 
} 
+0

對用戶說這是一個非常愚蠢的事情。 – SLaks

回答

3

不,您需要檢查是什麼類型的異常,並明確地捕捉。在異常消息中測試字符串是一個壞主意,因爲它們可能會從一個框架版本更改爲另一個版本。我確信微軟不保證消息永遠不會改變。

在這種情況下,看着docs你可能會得到無論是ArgumentNullExceptionArgumentException,所以你需要測試在你的try/catch塊:

try { 
    DoSomething(); 
} 
catch (ArgumentNullException) { 
    // Insult the user 
} 
catch (ArgumentException) { 
    // Insult the user more 
} 
catch (Exception) { 
    // Something else 
} 

你需要哪些異常這裏,我不知道。您需要相應地確定並構建您的SEH塊。但總是試圖捕捉異常,而不是它們的屬性。

注意最後的catch強烈建議;它確保如果發生其他事情發生,您將不會得到未處理的異常。

-1

是的,你可以再次從catch塊拋出異常,例如:

catch (SystemException ex) 
{ 
     if(ex.Message == "Path is not of legal form.") 
     { 
      throw new Exception("Hey you idiot, go into the application settings and specify a valid path", ex); 
     } 
     else 
     { 
      MessageBox.Show(ex.Message,"Error"); 
     } 
} 
0

您可以檢查參數異常

...catch (SystemException ex) 
{ 
    if(ex is ArgumentException) 
     { 
      MessageBox.Show("Hey you idiot, go into the application settings and specify a valid path","Error"); 
     } 
     else 
     { 
      MessageBox.Show(ex.Message,"Error"); 
     } 
} 
0

這是一個ArgumentException

catch (ArgumentException) { 
    MessageBox.Show("Please enter a path in settings"); 
} catch (Exception ex) { 
    MessageBox.Show("An error occurred.\r\n" + ex.Message); 
} 
0

一些方法去解決它。

首先,剛檢查設置您做出GetDirectories()電話之前先:

if(string.IsNullOrEmpty(Properties.Settings.Default.customerFolderDirectory)) 
{ 
    MessageBox.Show("Fix your settings!"); 
} 
else 
{ 
    string[] cPathDirectories = Directory.GetDirectories(Properties.Settings.Default.customerFolderDirectory); 
} 

或乘坐更具體的例外:

catch (ArgumentException ex) 
{ 
    MessageBox.Show("Hey you idiot, go into the application settings and specify a valid path","Error"); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.Message); 
} 

我可能會與前走,從此以後你不會碰到罰款(儘管很小),例外投擲,並可以做任何其他驗證,如檢查路徑是否存在等。

如果你更喜歡後者,雖然你可以找到例外的列表Directory.GetDirectories()拋出here,所以你可以適當地修改你的信息。

P.S.我也不會打電話給你的用戶笨蛋,但那是在你和你的上帝之間。 :)