How do I use ArgumentOutOfRangeException with multiple parameters?

I have the following code.

DoSomething(int min, int max)
{
    if (min < 1 || min > 5)
        throw new ArgumentOutOfRangeException("min");
    if (max < 1 || max > 5)
        throw new ArgumentOutOfRangeException("max");
    if (min > max)
        throw new ArgumentOutOfRangeException("min & max");

    DoSomethingWithYourLife(); // =)
}

      

In the documentation, I specify that min and max must be in the range [1-5] and max must be greater than or equal to min.

Is the third Exception constructed correctly? If not, how do I throw an Exception?

+3


source to share


2 answers


No, the constructor argument ArgumentOutOfRangeException

must always be one of the parameter names. You can choose any of them - I usually assume that the previous parameter is correct, so the later parameter is incorrect in relation to it. You can (and should) provide more information in the post. It's also very handy if you are giving the actual value - like so:

if (min < 1 || min > 5)
{
    throw new ArgumentOutOfRangeException("min", min, "min must be between 1 and 5 inclusive");
}
if (max < 1 || max > 5)
{
    throw new ArgumentOutOfRangeException("max", max, "max must be between 1 and 5 inclusive");
}
if (max < min)
{
    throw new ArgumentOutOfRangeException("max", max, "max must not not be less than min");
}

      

For Noda Time , I have helper methods for this, for example:



internal static void CheckArgumentRange(string paramName,
    int value, int minInclusive, int maxInclusive)
{
    if (value < minInclusive || value > maxInclusive)
    {
        throw new ArgumentOutOfRangeException(paramName, value,
            "Value should be in range [" + minInclusive + "-" + maxInclusive + "]");
    }
}

      

Thus, you can simplify the above:

Preconditions.CheckArgumentRange("min", min, 1, 5);
Preconditions.CheckArgumentRange("max", max, 1, 5);
if (max < min)
{
    throw new ArgumentOutOfRangeException("max", max, "max must not not be less than min");
}

      

+3


source


I would recommend just picking one of these, but providing a more informative error message this constructor overload :



if (min > max)
    throw new ArgumentOutOfRangeException("max", "max must be greater than or equal to min");

      

0


source