Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception type to throw if a list/collection is empty or null and cannot be iterated (not a parameter)?

Tags:

Suppose a simple example where a method retrieves a collection (such as a list containing some configuration strings) and tries to examine it in some way:

void Init() {     XmlDocument config = new XmlDocument();     config.Load(someXml);     var list = config.SelectNodes("/root/strings/key"); // Normally, list should not be null or empty      if (list == null || list.Count == 0)         throw new SomeExceptionType(message);   // What kind of exception to throw?      // Iterate list and process/examine its elements     foreach (var e in list) ... } 

In this specific instance, the method cannot continue normally if nothing was retrieved. I'm unsure what exception type to throw in such situations. My options are, as far as I know:

  • throw nothing manually and let NullReferenceException be thrown automatically (which doesn't handle empty list situation),

  • throw custom exception type (probably not a good idea, as I don't anticipate the caller will try to do anything about the exception, i.e. he won't be looking for a speecific exception type to handle),

  • do something else?
like image 420
w128 Avatar asked Sep 05 '13 13:09

w128


People also ask

How do you check if a list is null or empty?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.

How do you check if a list is empty or not in C#?

Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.

Can you throw an exception at any point?

RuntimeException and its subclasses are so-called unchecked exceptions: they can be thrown at any time, without the method that throws them having to explicitly declare that it may throw them, or without the surrounding code having to explicitly catch them. decalre that the method throws it.


2 Answers

Enumerable.First throws System.InvalidOperationException if the collection is empty. So could you, I guess.

throw new InvalidOperationException("Sequence contains no elements"); 

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first?view=netframework-4.8

like image 122
Zar Shardan Avatar answered Oct 15 '22 05:10

Zar Shardan


You can create your own exception type for appropriate logic:

public class InitializationException : Exception { } 

and then:

throw new InitializationException {Message = "Collection is empty"}; 
like image 23
Dzmitry Martavoi Avatar answered Oct 15 '22 07:10

Dzmitry Martavoi