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?

jonrsharpe's user avatar

jonrsharpe

124k31 gold badges283 silver badges491 bronze badges

Neptunium-Eater's user avatar

7

The getter must return a value or, alternatively, it can throw an exception. So, an easy way to handle it is to not catch exceptions and let them occur, or you can catch them and instead trow a more appropriate one.

You can also show a message box and then re-throw the exception like this:

try { ... } catch(Exception e) { Console.WriteLine(e.Message); throw; // re-throw this exception. }

Olivier Jacot-Descombes's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.