在维护我同事的代码时,甚至有人声称自己是高级开发人员,我经常看到以下代码:
try
{
//do something
}
catch
{
//Do nothing
}
或者有时他们将日志信息写入日志文件,例如下面的try catch块
try
{
//do some work
}
catch(Exception exception)
{
WriteException2LogFile(exception);
}
我只是想知道他们所做的是不是最好的做法?这让我很困惑,因为在我看来,用户应该知道系统发生了什么。
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.