【问题标题】:ArgumentException: Value does not fall within the expected range. - Fails to add strings to data structuresArgumentException:值不在预期范围内。 - 无法将字符串添加到数据结构
【发布时间】:2026-02-13 08:40:01
【问题描述】:

我有一个函数来创建一个图形,并使用StreamReader 将一些值添加到其他一些数据结构中,以从 .txt 文件中读取行。

public static DirectedGraph<string, bool> GetGraph(string fn)
{
    DirectedGraph<string, bool> dg = new DirectedGraph<string, bool>();
    ITrie trie = null;
    List<string> list = new List<string>();

    try
    {
        using (StreamReader sr = new StreamReader(fn))
        {
            string l;
            while((l = sr.ReadLine()) != null)
            {
                dg.AddNode(l);
                trie.Add(l);
                list.Add(l);
                GetEdges(list, trie, dg);
            }

            return dg;
        }

    } catch
    {
        throw new ArgumentException();
    }
}

我希望 StreamReader 将读取的值添加到列表中,trie 和图中的节点。 GetEdges() 是一个从给定列表中获取字符串并将边添加到图形数据结构中的函数。

【问题讨论】:

  • 欢迎来到 Stack Overflow。如果 anything 出了问题,你为什么要抛出ArgumentException?我强烈建议删除 try/catch 块 - 如果您让原始异常传播,它将更容易找出问题所在。
  • 请注意,虽然trienull,但trie.Add(l) 将抛出NullReferenceException,除此之外。
  • 你从来没有将trie设置为任何东西......
  • 是的,你得到了一个NullReferenceException,但由于你编写异常处理程序的方式,你永远不会知道它。为什么你捕获异常只是为了抛出一个不相关的空白异常?
  • 欢迎来到 Stack Overflow!把任何可能有问题的代码实践放在一边,恭喜你有一个格式良好、编写良好的问题!我们喜欢看到这样的事情。

标签: c# argumentexception


【解决方案1】:

正如@JonSkeet 和@RufusL 所指出的,trie 被实例化为null,并且由于它从未设置为任何东西,所以当trie.Add(l);仍然 null叫。这会抛出一个NullReferenceException,但由于try/catch 块,该异常被捕获,其数据被忽略,取而代之的是一个具有默认值的ArgumentException 被抛出。我强烈建议使用某种方式从原始异常中抛出或获取数据以进行调试。

【讨论】: