C# 自定义基于默认系统异常引发的错误

C# 自定义基于默认系统异常引发的错误,c#,error-handling,C#,Error Handling,我有一句话: string[]cPathDirectories=Directory.getdirectory(Properties.Settings.Default.customerFolderDirectory) 如果用户未指定搜索路径(此设置保存为String.Empty),则将抛出错误“Path not of legal form”。我想抛出这个错误,说“嘿,你这个白痴,进入应用程序设置并指定一个有效路径”。有没有办法做到这一点,而不是: ...catch (SystemException

我有一句话:
string[]cPathDirectories=Directory.getdirectory(Properties.Settings.Default.customerFolderDirectory)

如果用户未指定搜索路径(此设置保存为String.Empty),则将抛出错误“Path not of legal form”。我想抛出这个错误,说“嘿,你这个白痴,进入应用程序设置并指定一个有效路径”。有没有办法做到这一点,而不是:

...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");
      }
}

是的,您可以再次从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");
      }
}

您可以检查参数异常

...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");
      }
}

这是一个
参数异常

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

有两种方法可以解决这个问题

首先,在进行
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()
throws,这样您就可以适当地定制消息


另外,我也不会称你的用户为白痴,但这是你和你的上帝之间的事。:)

否,您需要检查异常的类型并显式捕获它。测试异常消息中的字符串是一个坏主意,因为它们可能会从框架的一个版本更改为另一个版本。我很确定微软并不保证信息永远不会改变

在这种情况下,请查看,您可能会得到
ArgumentNullException
ArgumentException
,因此您需要在try/catch块中测试:

try {
    DoSomething();
}
catch (ArgumentNullException) {
    // Insult the user
}
catch (ArgumentException) {
    // Insult the user more
}
catch (Exception) {
    // Something else
}
我不知道你需要什么例外。您需要确定这一点,并相应地构建SEH块。但始终尝试捕获异常,而不是它们的属性


注意:强烈建议使用最后一个
捕获
;它可以确保在发生其他情况时不会出现未经处理的异常。

对用户来说,这是一件非常愚蠢的事情。