gpt4 book ai didi

C#使用try-catch捕获异常的最佳实践?

转载 作者:行者123 更新时间:2023-11-30 13:30:32 27 4
gpt4 key购买 nike

假设我需要运行 methodA 并且 methodA 将抛出 FormatException。

如果我写这个 block :

try
{
methodA();
}
catch (Exception ex)
{
methodB();
}
catch (FormatException ex)
{
methodC();
}

它是否会运行 methodC,知道 FormatException 也是一个异常,因此将进入 methodB 的 catchblock。

还是这样写比较好:

try
{
methodA();
}
catch (Exception ex)
{
if(ex is FormatException)
{
methodC();
} else
{
methodB();
}
}

最佳答案

不,它永远不会运行 methodC,但是如果您交换 catch 的顺序,它会:

try
{
methodA();
}
catch (FormatException ex)
{
methodC();
}
catch (Exception ex)
{
methodB();
}

引用MSDN :

It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.

关于C#使用try-catch捕获异常的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32569650/

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