문제

I'm actually searching for a guidline, how to document multiple exceptions in a public method inside a C#-DLL.

example:

/// <summary>
/// This method does something
/// </summary>
/// <param name="p_Parameter1">First parameter</param>
/// <param name="p_Parameter2">Second parameter</param>
/// <param name="p_Number">A number</param>
/// <exception cref="ArgumentNullException">
/// Thrown if p_Parameter1 is null</exception>
/// <exception cref="ArgumentNullException">
/// Thrown if p_Parameter2 is null</exception>
/// <exception cref="ArgumentNullException">
/// Thrown if any element of p_Parameter2 is null</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if p_Number is below or equal 0</exception>
/// <returns>A object</returns>
public static object DoSomething(
    object p_Parameter1, IList<object> p_Parameter2, 
    object p_Parameter3, int p_Number)
{
    if(p_Parameter1 == null)
        throw new ArgumentNullException(
            paramName:"p_Parameter1", 
            message:"Parameter is needed");
    if (p_Parameter2 == null)
        throw new ArgumentNullException(
            paramName: "p_Parameter2", 
            message: "Parameter is needed");

    for (int i = 0; i < p_Parameter2.Count; i++)
    {
        if(p_Parameter2[i] == null)
            throw new ArgumentNullException(
                paramName: String.Format("p_Parameter2[{0}]", i),
                message: "All elements have to be initialized");
    }

    if(p_Number < 0)
        throw new ArgumentOutOfRangeException(
            paramName: "p_Number", 
            message: "Parameter should be bigger then zero");

    var returnValue = new object();

    // do something where p_Parameter3 == null is allowed

    return returnValue;
}

Is it the right way to document those exceptions? Should I add one exception-tag for each case, or should I add only one for all Parameters for which null-values ar not allowed?

/// <exception cref="ArgumentNullException">
/// Thrown if p_Parameter1, p_Parameter2
/// or any element of p_Parameter2 are null</exception>
도움이 되었습니까?

해결책

I would definitely group the exceptions by type, ie Thrown if p_Parameter1, p_Parameter2 or any element of p_Parameter2 are null.

As a reference, look at the documentation at MSDN. An example:

ArgumentNullException   |   Either path, contents, or encoding is null.

다른 팁

MSDN is a good source to emulate in this case, and taking a survey of a few functions there it looks like they tend to use one exception block and enumerate the different parameters inside of it.

Doing it this way makes it easier for consumers of your code to know what exceptions to possibly catch because seeing a list of distinct exceptions is easier to grok than a list that contains duplicates.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top