What exception type to throw if a list/collection is empty or null and cannot be iterated (not a parameter)?
You can create your own exception type for appropriate logic:
public class InitializationException : Exception
{
}
and then:
throw new InitializationException {Message = "Collection is empty"};
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
I'm not sure there is a single built-in exception you can elegantly throw in this case...a NullReferenceException
is inappropriate since an empty list is not a null reference
I would suggest going with Dmintry's proposed solution since the caller can still just use try...catch(Exception)
without having to know or care that the exception is really a SuperDooperListNullOrEmptyFunTimeException
Since this is either an unrecoverable error from the caller's point of view (i.e they have no control over the selected Xml path, and no control over what the XML is that's being loaded) then the exception is only going to be either dumped to a log or on-screen for human consumption, at which point it's moot - as the actual message is more important than the type.
On the other hand, if it is recoverable (caller can re-try the method after having made sure that the xml to load now contains the correctly formatted xml, or caller can notify the user and ask them to go and fix the XML and "would you like to retry now?" kind of thing) then you need to give them a typed exception so they know it's safe to retry as opposed to a plain old Exception which could mean something else went horribly wrong and retrying will only make things worse...