运维开发网

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

运维开发网 https://www.qedev.com 2020-05-12 13:44 出处:网络 作者:运维开发网整理
假设我需要运行methodA,而methodA将抛出FormatException. 如果我写这个块: try { methodA(); } catch (Exception ex) { methodB(); } catch (FormatException ex) { methodC(); } 它是否会运行methodC,知道FormatException也是一个Exce
假设我需要运行methodA,而methodA将抛出FormatException.

如果我写这个块:

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

它是否会运行methodC,知道FormatException也是一个Exception,因此将进入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.

0

精彩评论

暂无评论...
验证码 换一张
取 消