如果列表/集合为空或为null且无法迭代(不是参数),则抛出什么异常类型?

w12*_*128 13 c# exception-handling

假设一个简单的示例,其中方法检索集合(例如包含一些配置字符串的列表)并尝试以某种方式检查它:

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) ...
}
Run Code Online (Sandbox Code Playgroud)

在此特定实例中,如果未检索到任何内容,则该方法无法正常继续.我不确定在这种情况下抛出什么异常类型.据我所知,我的选择是:

  • 手动抛出任何东西,让它NullReferenceException自动抛出(不处理空列表情况),

  • 抛出自定义异常类型(可能不是一个好主意,因为我不期望调用者会尝试对异常做任何事情,即他不会寻找一个特殊的异常类型来处理),

  • 做点什么?

Zar*_*dan 12

Enumerable.FirstSystem.InvalidOperationException如果集合为空,则抛出。你也可以,我猜。

throw new InvalidOperationException("Sequence contains no elements");
Run Code Online (Sandbox Code Playgroud)

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


Dzm*_*voi 10

您可以为适当的逻辑创建自己的异常类型:

public class InitializationException : Exception
{
}
Run Code Online (Sandbox Code Playgroud)

然后:

throw new InitializationException {Message = "Collection is empty"};
Run Code Online (Sandbox Code Playgroud)