I've been creating a basic version of a LinkedList class mainly for the sake of an assignment (though also to gain a better understanding of it all). I've gotten to the stage where I'm writing error handling into everything where necessary, and the part that I've been struggling most with is the linked list's indexer property, but specifically the "Get" part of it (only showing the indexer itself because I think that's the only relevant section):
/// <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);
}
}
}
The reason as to why I show the 'Set' part of the indexer is because as you can see, both of them generally use the same type of logic when it comes to catching and handling errors. The weird part? The Get block gets a CSO161 "Not all code paths return a value" error whereas the Set block does not. What would be the best way to alter the Get block code to resolve this error?
List<T>.Item[Int32]which throws anArgumentOutOfRangeExceptionfor invalid indices. Also, if you want to avoid code duplication in the setters & getters you could extract an internal method returning theCustomLinkedNode<T>for the specified index like so: dotnetfiddle.net/sk0c3Z.Tto return from yourCustomLinkedList<T>when an invalid index is passed in. But is it wise? I'd argue not. At such a low level, any errors inside your list indexer are likely due to some bug inCustomLinkedList<T>itself or its immediate callers and so by swallowing the exception you would only be covering up the problem.