在维护我同事的代码时,甚至有人声称自己是高级开发人员,我经常看到以下代码:

try
{
  //do something
}
catch
{
  //Do nothing
}

或者有时他们将日志信息写入日志文件,例如下面的try catch块

try
{
  //do some work
}
catch(Exception exception)
{
   WriteException2LogFile(exception);
}

我只是想知道他们所做的是不是最好的做法?这让我很困惑,因为在我看来,用户应该知道系统发生了什么。


当前回答

对于异常,我尝试如下:

首先,我捕获特殊类型的异常,如除零、IO操作等,并根据这些编写代码。例如,除以0,这取决于我可以提醒用户的值的出处(例如,一个简单的计算器在中间计算(而不是参数)中到达一个除以0),或者静默地处理这个异常,记录它并继续处理。

然后我尝试捕获剩余的异常并记录它们。如果可能,允许执行代码,否则提醒用户发生错误,并要求他们发送错误报告。

在代码中,是这样的:

try{
    //Some code here
}
catch(DivideByZeroException dz){
    AlerUserDivideByZerohappened();
}
catch(Exception e){
    treatGeneralException(e);
}
finally{
    //if a IO operation here i close the hanging handlers for example
}

其他回答

更好的方法是第二种(指定异常类型的方法)。这样做的好处是,您知道这种类型的异常可以发生在您的代码中。您正在处理这种类型的异常,您可以继续。如果出现任何其他异常,那么这意味着有错误,这将帮助您找到代码中的错误。应用程序最终会崩溃,但你会知道你错过了什么(bug),需要修复。

我知道这是一个老问题,但这里没有人提到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.

您应该考虑这些异常的设计指南

异常抛出 使用标准异常类型 异常和性能

https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions