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

Edw*_*ard 3 .net c# exception-handling exception try-catch

假设我需要运行methodA,而methodA将抛出FormatException.

如果我写这个块:

try
{
    methodA();
}
catch (Exception ex)
{
    methodB();
}
catch (FormatException ex)
{
    methodC();
}
Run Code Online (Sandbox Code Playgroud)

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

或者这样写它更好:

try
{
    methodA();
}
catch (Exception ex)
{
    if(ex is FormatException)
    {
        methodC();
    } else
    {
        methodB();
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ych 10

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

try
{
    methodA();
}
catch (FormatException ex)
{
    methodC();    
}
catch (Exception ex)
{
    methodB();
}
Run Code Online (Sandbox Code Playgroud)

引用MSDN:

可以在同一个try-catch语句中使用多个特定的catch子句.在这种情况下,catch子句的顺序很重要,因为catch子句是按顺序检查的.在不太具体的例外之前捕获更具体的例外.如果您订购了catch块,编译器会产生错误,以便永远无法访问以后的块.