Commenting out try catch statements

What is the appropriate place to explain error handling in a try-catch statement? It looks like you could add explanatory comments either at the beginning of the try block or in the catch block.

// Possible comment location 1 try { // real code } // Possible comment location 2 catch { // Possible comment location 3 // Error handling code } 
+4
source share
8 answers

I usually do the following. If only one exception is handled, I usually don’t worry, as it should be self-documenting.

 try { real code // throws SomeException real code // throws SomeOtherException } catch(SomeException se) { // explain your error handling choice if it not obvious } catch(SomeOtherException soe) { // explain your error handling choice if it not obvious } 
+17
source

"Commentary is a lie . " Work on these variable names and common logic to avoid this. And if you really need to lie, do it inside the catch block.

+10
source

I do not think this is important.

I think that the imported thing that you need to remember with the comments is the address why the code is what it is and not what the code does in the first place. This does not mean that you should not explain complex logic in a brief comment, but why it is much more important.

+5
source

How to simply configure the code so that it does not need additional comments?

 try { performDifficultAct( parameter ); } catch (ArgumentOutOfRangeException couldNotFindArgument) { // handle exception } catch (Exception otherUnknownException ) { // handle exception } 

No need to document if you can use your variable and method name to show what is happening. No need to document if you have to register or create exceptions - in any case, the registration message in the source code should be taken for granted. The only time you need additional documentation in your code is it’s completely unclear what the code is doing, or ther is an easy-to-use mission or an ambiguous step that you need to add, which will require explanation for those looking at the code in the future .

Edit: To clarify a bit, a little more about how I can use these catch statements to provide useful information to both the maintenance programmer and users / support / QA / anyone who uses the software. It also shows a situation in which I absolutely would like to add additional comments to the code:

 public void PerformSomeActionOrOther(string parameter) { try { // For some reason an eleven character string causes a bluescreen from Kernel32 if (parameter.Length==11) parameter+=" "; performDifficultAct( parameter ); } catch (ArgumentOutOfRangeException couldNotFindArgument) { this.Log.WriteLn("Argument out of range exception in ArbitraryClass.PerformSomeActionOrOther"); this.Log.WriteLn(String.Format("Probable cause is that {0} is not in the array", parameter)); this.Log.WriteLn(String.Format("Exception: {0}", couldNotFindArgument.Message)); } catch (Exception otherUnknownException ) { this.Log.WriteLn("Unexpected exception in ArbitraryClass.PerformSomeActionOrOther"); this.Log.WriteLn(String.Format("Exception: {0}", otherUnknownException.Message)); throw( otherUnknownException ); } } 
+4
source

Definitely do not comment on the top because you can usefully say other than "launch an exception handling block here"? Comments on catch statements are better, but overall, again, what are you going to say? "Handle a NullPointerException"?

I would go for an IFF comment, you need to say that you are doing something exciting, like a chain to exclude an application area.

+2
source

I think a well-written attempt / catch should be concise and specific. I agree with @Jason that why is more important, but it is equally important to keep the code inside catch as concise as possible.

It would also help if you used certain exceptions to capture. If you use Java, for example, try catching a NullPointerException, rather than a general exception. This should explain why try catch exists and what you do to solve it.

+1
source

Location doesn’t matter if you agree. My personal preferences are as follows:

 //comment 1: code does XYZ, can cause exceptions A, B, C try { //do something } //comment 2: exception A occurs when foo != bar catch (ExceptionA a) { //do something } //comment 3: exception B occurs when bar is null catch (ExceptionB b) { //do something } //comment 4: exception B occurs when foo is null catch (ExceptionC c) { //do something } 
+1
source

I know that this is not the answer you are looking for, but do not comment at all. If your code is not clear enough to stand without comment, then you should reorganize it until it is. Jeffrey Palerm o just wrote a blog post that said it best.

Typically, comments tend to document either:

  • Code that is too compact. Things that look like this: ++i?--g:hi;
  • Long blocks of code to be summarized.
  • Code that is either one-time or has no clear reason for existing

The following is a simplified example of simply 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 encourage reuse, you essentially need to support both code and comments. It is possible (and preferable) to reorganize it so that it is clearer without comment.

 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 a lot of code for very subtle benefits, but the benefits cannot be overestimated. The code is also understandable, but you get the advantage that you do not need to have a separate set of metadata (comments) to explain the code. The code explains itself. If your catch code block is too long and needs comments to be generalized, consider refactoring it for a separate method to improve readability.

0
source

All Articles