特定异常类型的异常处理

时间:2021-02-18 11:50:40

标签: c# exception

我需要捕获一个通用异常,然后基于特定类型进行分类以减少代码行数,因为所有异常都做同样的事情。

类似于下面的内容

catch (Exception ex)
        {
            Type ExceptionType = ex.GetType();
           switch (ExceptionType.ToString())
            {
                 
                case "IOException":
                case "NullReferenceException":
                system.WriteLine((ExceptionType)ex.Message);
                break;
    }

这显示错误没有类型异常类型。是否有可能尝试这种方法并实现这一点,或者需要采取典型的 if else 方法。 请帮忙

2 个答案:

答案 0 :(得分:3)

理想情况下,您应该像这样单独处理每个异常:

try
{
    
}
catch (IOException ex)
{
    // Log specific IO Exception
}
catch (NullReferenceException ex)
{
    // Log Specific Null Reference Exception
}
catch (Exception ex)
{
    // Catch everything else
}

你可以这样做:

    string exceptionErrorMessage;
    
    try
    {
    
    }
    catch (IOException ex)
    {
        // Log specific IO Exception
        exceptionErrorMessage = ex.Message;
    }
    catch (NullReferenceException ex)
    {
        // Log Specific NullReferenceException
        exceptionErrorMessage = ex.Message;
    }
    catch (Exception ex)
    {
        // Catch everything else
        exceptionErrorMessage = ex.Message;
    }
    
    if (!string.IsNullOrEmpty(exceptionErrorMessage))
    {
        // use your logger to log exception.
        Console.WriteLine(exceptionErrorMessage);
    }

这是使用他想要的相同方法对 OP 代码进行正确处理的代码:

try
{

}
catch (Exception e)
{
    var exType = e.GetType().Name;
    switch (exType)
    {
        case "IOException":
        case "NullReferenceException":
            Console.WriteLine(e.Message);
            break;
    }
}

答案 1 :(得分:-1)

听起来您可能正在寻找 ex.GetType().Name!

就完整解决方案而言,这应该适用于您现有的代码。

相关问题