自定义基于默认SystemExceptions抛出的错误

时间:2012-08-22 23:48:23

标签: c# error-handling

我有一条线: 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");
      }
}

5 个答案:

答案 0 :(得分: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 :(得分: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");
      }
}

答案 2 :(得分:0)

这是ArgumentException

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

答案 3 :(得分: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。我也不会打电话给你的用户白痴,但这是你和你的上帝之间。 :)

答案 4 :(得分:-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");
      }
}