c# - 如何将 ArgumentOutOfRangeException 与多个参数一起使用?

标签 c# exception

我有以下代码。

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(); // =)
}

在文档中我声明最小值和最大值必须在 [1-5] 范围内,并且最大值必须大于或等于最小值。

第三个异常是否构造正确?如果不是,我应该如何构造异常?

最佳答案

不,ArgumentOutOfRangeException 构造函数的参数应该始终是参数名称之一。您可以选择其中任何一个 - 我通常假设 earlier 参数是正确的,因此 later 参数相对于它是不正确的。不过,您可以(并且应该)在消息中提供更多信息。如果您提供实际值,它也真的很方便 - 所以:

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

对于 Noda Time ,我有一些辅助方法,例如:

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

这样你就可以将上面的内容简化为:

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

关于c# - 如何将 ArgumentOutOfRangeException 与多个参数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26025561/

相关文章:

c# - 输入字符串的格式不正确?

visual-studio - complus异常代码-532462766

ios - Swift WKWebView 在 didFailProvisionalNavigation 上崩溃

java - 捕获 NumberFormatException 是一种不好的做法吗?

c# - ASP.NET 自定义 404 返回 200 OK 而不是 404 Not Found

c# - 我不明白为什么会出现此 "An Object Reference is Required"错误

c# - Windows 窗体 C# : Resize Label image on runtime when resizing the label

c# - 无法将对象加载到 Asp.net 上的 Redis session 状态提供程序

python - 如何将 traceback/sys.exc_info() 值保存在变量中?

c++ - 无法抛出 CException 派生异常?