在维护我同事的代码时,甚至有人声称自己是高级开发人员,我经常看到以下代码:
try
{
//do something
}
catch
{
//Do nothing
}
或者有时他们将日志信息写入日志文件,例如下面的try catch块
try
{
//do some work
}
catch(Exception exception)
{
WriteException2LogFile(exception);
}
我只是想知道他们所做的是不是最好的做法?这让我很困惑,因为在我看来,用户应该知道系统发生了什么。
我知道这是一个老问题,但这里没有人提到MSDN的文章,实际上是文档为我澄清了这个问题,MSDN在这方面有一个非常好的文档,当以下条件为真时,你应该捕获异常:
您已经很好地理解了异常可能被抛出的原因,并且可以实现特定的恢复,例如在捕获FileNotFoundException对象时提示用户输入一个新的文件名。
您可以创建并抛出一个新的、更具体的异常。
int GetInt(int[] array, int index)
{
try
{
return array[index];
}
catch(System.IndexOutOfRangeException e)
{
throw new System.ArgumentOutOfRangeException(
"Parameter index is out of range.");
}
}
您希望在将异常传递给其他处理之前对其进行部分处理。在下面的示例中,catch块用于在重新抛出异常之前向错误日志添加条目。
try
{
// Try to access a resource.
}
catch (System.UnauthorizedAccessException e)
{
// Call a custom error logging procedure.
LogError(e);
// Re-throw the error.
throw;
}
我建议阅读整个“异常和异常处理”部分以及异常的最佳实践。
To me, handling exception can be seen as business rule. Obviously, the first approach is unacceptable. The second one is better one and it might be 100% correct way IF the context says so. Now, for example, you are developing an Outlook Addin. If you addin throws unhandled exception, the outlook user might now know it since the outlook will not destroy itself because of one plugin failed. And you have hard time to figure out what went wrong. Therefore, the second approach in this case, to me, it is a correct one. Beside logging the exception, you might decide to display error message to user - i consider it as a business rule.