Commenting try catch statements

2019-05-07 21:24发布

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

}

8条回答
2楼-- · 2019-05-07 21:53

The location does not matter as long as you are consistent. My personal preference is 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
}
查看更多
ら.Afraid
3楼-- · 2019-05-07 21:55

What about just setting up the code so it doesn't need extra 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 naming to show what is going on. No need to document if you are having to log or raise the exceptions - the logging message in the source code should be self-explanatory anyway. The only time you should need extra documentation in your code is when it is totally non-obvious what the code is doing or ther is an easy-to-miss gotcha or ambiguous step you have to add that will need explanation for anyone looking at the code in future.

Edit: To clarify a little, here's a bit more of how I might use those "catch" statements to provide useful information both to a maintenance programmer and to users/support/QA/anyone else who uses the software. Also an illustration of the kind of situation where I absolutely would want to add extra comments in 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 );
  }
}
查看更多
登录 后发表回答