如何对C#中的特定异常采取行动?

iha*_*yet 2 c# exception-handling exception

我曾经在C#面临一个特殊的例外 - 例如 - "The underlying connection was closed: An unexpected error occurred on a receive."

如何确保仅在出现此异常时才进行特定的校正任务?我一直在通过比较错误消息和预定义的字符串来解决问题.例如 -

    catch(Exception e)
    {
        if(e.Message=="...")
        {  
            //correction routine
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,这似乎不是传统方式.任何指南都将非常感激.谢谢.

D S*_*ley 5

这是C#6.0之前的传统方式(除了可能捕获更具体的异常类型).在C#6.0中,您可以添加异常过滤器:

catch (Exception ex) if (ex.Message.Contains("The underlying connection was closed"))
{
    //correction routine 
}
Run Code Online (Sandbox Code Playgroud)

但是,可能有比检查消息更安全的方法.看看,ErrorCode看看你是否无法过滤(因为它不受文化的影响).

catch (Exception ex) if (ex.ErrorCode == 1234)
{
    //correction routine 
}
Run Code Online (Sandbox Code Playgroud)