c#使用try-catch捕获异常的最佳实践?
c# Best practice of catching exceptions with try-catch?
假设我需要 运行 methodA 并且 methodA 将抛出 FormatException。
如果我写这个块:
try
{
methodA();
}
catch (Exception ex)
{
methodB();
}
catch (FormatException ex)
{
methodC();
}
它会不会 运行 methodC,知道 FormatException 也是一个异常,因此会进入 methodB[=23= 的 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.
catch块总是根据特定异常执行。
所有异常都来自 System.Exception class 所以它应该在你的最后一个 catch 块中。
所有其他 catch 块都应该是您假定的特定异常 class(在您的情况下是 FormatException),可以由您的方法调用。
戴夫的回答是一个完美的例子,而且如果你的 catch 块中的异常有一些层次关系,那么最好以相反的层次顺序重新排列它们。
假设我需要 运行 methodA 并且 methodA 将抛出 FormatException。
如果我写这个块:
try
{
methodA();
}
catch (Exception ex)
{
methodB();
}
catch (FormatException ex)
{
methodC();
}
它会不会 运行 methodC,知道 FormatException 也是一个异常,因此会进入 methodB[=23= 的 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.
catch块总是根据特定异常执行。
所有异常都来自 System.Exception class 所以它应该在你的最后一个 catch 块中。
所有其他 catch 块都应该是您假定的特定异常 class(在您的情况下是 FormatException),可以由您的方法调用。
戴夫的回答是一个完美的例子,而且如果你的 catch 块中的异常有一些层次关系,那么最好以相反的层次顺序重新排列它们。