gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:38:51 24 4
gpt4 key购买 nike

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

请引用以下使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com