I know this isn't the answer you're looking for, but don't comment at all. If your code isn't clear enough to stand on its own without commenting, then you should refactor it until it is. Jeffrey Palermo just wrote a blog post that states it best.
Typically, comments tend to document either:
- Code that's too compact. Things that look like this:
++i?--g:h-i;
- Long blocks of code that need to be summarized
- Code that is either disposable or has no clear reason for existing
See below for a simplified example of some simple commenting on your exception block, and a version that eliminates the need for comments.
bool retries = 0;
while (retries < MAX_RETRIES)
{
try
{
... database access code
break;
}
// If under max retries, log and increment, otherwise rethrow
catch (SqlException e)
{
logger.LogWarning(e);
if (++retries >= MAX_RETRIES)
{
throw new MaxRetriesException(MAX_RETRIES, e);
}
}
// Can't retry. Log error and rethrow.
catch (ApplicationException e)
{
logger.LogError(e);
throw;
}
}
While the above comments promote reusability, you essentially have to maintain both the code and the comments. It is possible (and preferable) to refactor this so that it is clearer without comments.
bool retries = 0;
while (canRetry(retries))
{
try
{
... database access code
break;
}
catch (SqlException e)
{
logger.LogWarning(e);
retries = incrementRetriesOrThrowIfMaxReached(retries, e);
}
catch (ApplicationException e)
{
logger.LogError(e);
throw;
}
}
...
private void incrementRetriesOrThrowIfMaxReached(int retries, Exception e)
{
if (++retries >= MAX_RETRIES)
throw new MaxRetriesException(MAX_RETRIES, e);
return retries;
}
private bool canRetry(int retries)
{
return retries < MAX_RETRIES;
}
The latter example may seem like more code for a very subtle benefit, but the gains can't be overstated. The code is just as understandable, but you have the benefit that you don't need to have a separate set of metadata (comments) in order to explain the code. The code explains itself. If your catch code block is too long and needs comment to summarize, think about refactoring it to a separate method in order to improve readability.