在索引器Get访问器中使用try-catch块的最佳实践

编程语言 2026-07-11

我一直在为一个作业(同时也为了更好地理解这一切)创建一个基本版本的LinkedList类。现在到了需要在一切地方加入错误处理的阶段,我头疼的部分主要是链表的索引器属性,尤其是它的Get部分(这里只展示索引器本身,因为我认为这是唯一相关的部分):

/// <summary>
/// Indexer that allows you to either retrieve or set the data of a node 
/// within the linked list
/// </summary>
/// <param name="index">the index of the node to be retrieved or changed</param>
/// <returns></returns>
/// <exception cref="Exception">Throws exception if faulty index or value given.</exception>
public T this[int index]
{
    get
    {
        try
        {
            if (index < 0) { throw new Exception("Index cannot be less than 0"); }
            else if (head is null) { throw new Exception("This list has no items in it."); }
            else if (index >= Count) { throw new Exception("Index overflow (too high)."); }
            else if (index == 0) { return head.Data; }
            else if (index == count - 1) { return tail.Data; }
            else
            {
                CustomLinkedNode<T> current = head;
                for (int currNum = 0; currNum < index; currNum++)
                {
                    current = current.Next;
                }
                return current.Data;
            }
        } catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    set
    {
        try
        {
            if (index < 0) { throw new Exception("Index cannot be less than 0"); }
            else if (head is null) { throw new Exception("This list has no items in it."); }
            else if (index >= Count) { throw new Exception("Index overflow (too high)."); }
            else
            {
                CustomLinkedNode<T> current = head;
                for (int currNum = 0; currNum < index; currNum++)
                {
                    current = current.Next;
                }
                current.Data = value;
            }
        } catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

之所以展示索引器的Set部分,是因为如你所见,在捕获和处理错误方面,它们通常使用相同类型的逻辑。奇怪的地方?Get块会得到CSO161“并非所有代码路径都会返回一个值”的错误,而Set块则没有。要怎样改动Get块的代码以解决这个错误才是最佳做法?

解决方案

Getter(获取器)必须返回一个值,或者也可以抛出一个异常。因此,一种简单的处理方式是让异常直接抛出,不进行捕获,或者你也可以捕获异常并改为抛出一个更合适的异常。

你也可以显示一个消息框,然后按如下方式重新抛出异常:

try
{
   ...
} catch(Exception e)
{
    Console.WriteLine(e.Message);
    throw; // re-throw this exception.
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章