c# - 在 C# 的 try/catch block 中检查异常类型

标签 c# exception try-catch

我一直在思考一个相当基本的问题。

请引用以下使用 try/catch block 的代码片段:

public void doSomething()  
{  
   try
    {
        doSomethingElse()
    }
    catch (Exception ex)
    {
        if (ex is IndexOutOfRangeException || ex is DivideByZeroException || ex is Exception)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

1) 如果我只想将异常消息输出到控制台,是否有必要在 if 子句中检查我得到的异常类型,或者我可以直接做

...
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
...

2) 据我了解,如果我需要将定义的消息输出到控制台而不是使用异常消息本身,则应该使用检查特定的异常类型 - 类似于

...
    catch (Exception ex)
    {
        switch (ex):
        {
            case IndexOutOfRangeException:
                Console.WriteLine("Personalized message #1");               
                break;
            case DivideByZeroException:
                Console.WriteLine("Personalized message #2");               
                break;
            case Exception:
                Console.WriteLine("Personalized message #3");               
                break;
        }
    }
...

非常感谢您对 1) 和 2) 的评论。感谢您的宝贵时间。

最佳答案

1) If all I want to do is output the exception message to the console, is it necessary to check in the if clause what type of Exception I'm getting

不,如果您只想显示其消息,则无需检查每个异常类型。只需使用 Exception.Message 属性。

2) it is my understanding that checking the specific exception type should be used if I need to output a defined message to the console instead of using the exception message itself

与其捕获基础异常然后比较不同类型的异常,首先捕获特定异常然后在每个 catch block 中结束基础

try
{

}
catch (IndexOutOfRangeException indexOutOfRangeException)
{
      //Specific handling
}
catch (DivideByZeroException divideByZeroException)
{
      //Specific handling
}
catch (Exception ex)
{
      //Exception handling for all other cases
}

关于c# - 在 C# 的 try/catch block 中检查异常类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30781032/

相关文章:

c# - 泛型和转换

c# - 区分x :Name and Name in Wpf application

c# - 如何在 C# 中管理外部 Windows 应用程序?

c# - 获取月初和月末日期的最简单方法是什么?

exception - SubSonic 3.0.0.3 更新异常

c# - System.Drawing.Image 异常

android - BaseTransientBottomBar 和相关错误以及如何解决

c++ - 无法从 main.cpp 中的共享库捕获异常

java - 黑莓中异步列表字段实现时出现 IllegalThreadStateException

java - try/catch 中未初始化的变量,带有未处理的异常