C#异常处理,哪个catch子句使用?

Ell*_*678 7 c# exception-handling

可能重复:
在c#中捕获特定异常与一般异常

这是一个示例方法

private static void outputDictionaryContentsByDescending(Dictionary<string, int> list)
{
    try
    {
        //Outputs entire list in descending order
        foreach (KeyValuePair<string, int> pair in list.OrderByDescending(key => key.Value))
        {
            Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message, "Error detected", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道除了Exception使用更具体的catch子句有什么优势之外还要使用什么异常子句.

编辑:好的,谢谢大家

Jus*_*ner 7

在语句中捕获各种类型的异常将允许您以不同的方式处理每个异常.

一条毯子规则对于Exception记录和重新抛出异常可能很有用,但对于实际处理您可以从中恢复的异常并不是最好的.

try
{
    // open a file specified by the user
}
catch(FileNotFoundException ex)
{
    // notify user and re-prompt for file
}
catch(UnauthorizedAccessException ex)
{
    // inform user they don't have access, either re-prompt or close dialog
}
catch(Exception ex)
{
    Logger.LogException(ex);
    throw;
}
Run Code Online (Sandbox Code Playgroud)


3Da*_*ave 2

我在您的示例中看到的异常的唯一潜在原因是 iflist为 null。OrderByDescending()应该返回一个空引用IEnumerable<>而不是空引用。

如果我读得正确,那么捕获以下内容可能更有意义NullReferenceException

try
{
...
} catch (NullReferenceException exception)
{
  MessageBox.Show(...);
}
Run Code Online (Sandbox Code Playgroud)

然而,这实际上取决于您的应用程序的需求。如果您的目的只是提醒用户或记录所有异常,那么捕获该类Exception就可以了。如果您需要对不同类型的异常进行特殊处理 - 例如发送电子邮件警报而不仅仅是记录消息 - 那么使用特定的异常类型是有意义的:

try
{
} 
catch(NullReferenceException e)
{
//...
} 
catch(StackOverflowException e)
{
//...
}
catch(Exception e)
{
/// generic exception handler
}
Run Code Online (Sandbox Code Playgroud)