Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ArgumentOutOfRangeException with multiple params?

Tags:

c#

exception

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 state that min and max must be on the [1-5] range, and max has to be greater or equal to min.

Is the third Exception correctly constructed? If not, how should I construct the Exception?

like image 863
Guillermo Mestre Avatar asked Sep 24 '14 20:09

Guillermo Mestre


1 Answers

No, the argument for the ArgumentOutOfRangeException constructor should always be one of the parameter names. You can pick either of them - I usually assume that the earlier parameter is correct, so the later parameter is incorrect in relation to it. You can (and should) give more information in the message though. It's also really handy if you give the actual value - 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, such as:

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 + "]");
    }
}

That way you could simplify the above to:

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");
}
like image 182
Jon Skeet Avatar answered Oct 29 '22 15:10

Jon Skeet