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

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
}

其他回答

对于异常,我尝试如下:

首先,我捕获特殊类型的异常,如除零、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
}

第二种方法很好。

如果你不想显示错误,并通过显示运行时异常(即。错误),这与他们无关,然后只记录错误,技术团队可以寻找问题并解决它。

try
{
  //do some work
}
catch(Exception exception)
{
   WriteException2LogFile(exception);//it will write the or log the error in a text file
}

我建议您对整个应用程序采用第二种方法。

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

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.

最佳实践是在错误发生时抛出异常。因为发生了一个错误,它不应该被隐藏。

但在现实生活中,你可以有几种情况想要隐藏它

您依赖于第三方组件,并且希望在出现错误时继续执行程序。 您有一个业务案例,需要继续进行,以防出现错误