简体   繁体   English

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

[英]c# Best practice of catching exceptions with try-catch?

Lets say I need to run methodA and methodA will throw a FormatException. 假设我需要运行methodA,而methodA将抛出FormatException。

If I write this block: 如果我写这个块:

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

Will it ever run methodC , knowing that FormatException is also an Exception and therefor will go into the catchblock of methodB . 它是否会运行methodC ,知道FormatException也是一个Exception,因此将进入methodB的catchblock

Or is it better to write it like this: 或者这样写它更好:

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

No, it won't ever run methodC , but if you swap the order of your catch 's it will: 不,它不会运行methodC ,但是如果你交换了catch的顺序,它会:

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

To quote MSDN : 引用MSDN

It is possible to use more than one specific catch clause in the same try-catch statement. 可以在同一个try-catch语句中使用多个特定的catch子句。 In this case, the order of the catch clauses is important because the catch clauses are examined in order. 在这种情况下,catch子句的顺序很重要,因为catch子句是按顺序检查的。 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. 如果您订购了catch块,编译器会产生错误,以便永远无法访问以后的块。

The catch block are always executed according to specific exception. catch块总是根据特定的异常执行。

All the Exceptions are derived from System.Exception class so it should be in the last of your catch blocks. 所有异常都是从System.Exception类派生的,因此它应该位于最后一个catch块中。

All other catch blocks should of a specific Exception class (FormatException in your case) that you presumed, could be invoked by your method. 所有其他catch块应该是您所假定的特定Exception类(在您的情况下为FormatException),可以由您的方法调用。

Dave's Answer is a perfect example for it and also if Exceptions in your catch blocks have some hierarchical relation then better reorder them in a reverse hierarchical order. Dave的答案是一个完美的例子,如果你的catch块中的异常有一些层次关系,那么最好以反向层次顺序重新排序它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM