What is the proper place to explain error handling in a try-catch statement? It seems like you could put explanatory comments at either the beginning of the try block or the catch block.
// Possible comment location 1
try
{
// real code
}
// Possible comment location 2
catch
{
// Possible comment location 3
// Error handling code
}
I usually do the following. If there's only one exception being handled, I usually don't bother since it should be self-documenting.
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:
++i?--g:h-i;
See below for a simplified example of some simple commenting on your exception block, and a version that eliminates the need for comments.
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.
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.
"A comment is a lie". Work on those variable names and the general logic so you can avoid it. And if you really need to lie, do it inside the catch block.
I think a well written try/catch should be concise and specific. I agree with @Jason that the why is more important but equally, it is important to keep the code inside catch as concise as possible.
It would also help if you used specific exceptions to be caught. If you are using Java for example, try to catch a NullPointerException rather than a generic Exception. This should explain why the try catch exists and what you are doing to resolve it.
Definitely don't comment the top of it, because what can you usefully say except "starting an exception handling block here"? Comments on the catch statements are better, but in general, again, what are you gonna say? "Handle a NullPointerException"?
I'd go for a comment IFF you need to say that you're doing something exciting, like chaining to an application-domain exception.
I don't think it matters, at all.
I think the import thing to remember with commenting is to address why the code is the way it is and not what the code is doing, first and foremost. This is not to say you shouldn't explain complex logic in a concise comment, but the why is so much more important.