代码之家  ›  专栏  ›  技术社区  ›  Dan Tao

当你知道你调用的方法只会抛出相同的东西时,你会抛出一个异常吗?

  •  1
  • Dan Tao  · 技术社区  · 14 年前

    假设我有这样的方法*:

    public T GetItem(int index)
    {
        if (index < 0 || index >= _privateList.Count)
        {
            throw new ArgumentOutOfRangeException("index");
        }
    
        return _privateList[index];
    }
    

    包括那个吗 throw 还是不说?一方面,我觉得马上处理无效的输入很好,因为这样可以让您在编写实际的实现代码时对正在处理的内容更加自信。但在这种情况下,如果省略边界检查,最终结果将非常相同(即 列表 会把 ArgumentOutOfRangeException 而不是封闭类型)。

    此外,由于上面的代码正在检查我,开发人员, 知道 无论如何都会被检查(在呼叫中) _privateList[index] )似乎我在使代码比上面所需要的工作更多,基本上执行了两次完全相同的比较集。

    对这方面的任何指导都将不胜感激。

    *具体来说,我说的是.NET(c),但我想相同或类似的问题可能会被问到许多不同的语言/框架,因此“语言不可知”标签。

    4 回复  |  直到 14 年前
        1
  •  2
  •   Hans Passant    14 年前

        2
  •  5
  •   Dialecticus    14 年前

        3
  •  3
  •   CodesInChaos    14 年前

        4
  •  1
  •   Bevan    14 年前

    public OrderLine GetOrderLineint index)
    {
        if (index < 0 || index >= _privateList.Count)
        {
            throw new ArgumentOutOfRangeException(
                "index",
                "No OrderLine available at index " + index.ToString());
        }
    
        return _privateList[index];
    }
    

    推荐文章