Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ArgumentException:值不在预期范围内。-无法将字符串添加到数据结构_C#_Argumentexception - Fatal编程技术网

C# ArgumentException:值不在预期范围内。-无法将字符串添加到数据结构

C# ArgumentException:值不在预期范围内。-无法将字符串添加到数据结构,c#,argumentexception,C#,Argumentexception,我有一个函数,可以创建一个图形,并使用StreamReader从.txt文件中读取行,将一些值添加到其他一些数据结构中 public static DirectedGraph<string, bool> GetGraph(string fn) { DirectedGraph<string, bool> dg = new DirectedGraph<string, bool>(); ITrie trie = null; List<s

我有一个函数,可以创建一个图形,并使用
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();
    }
}

公共静态DirectedGraph GetGraph(字符串fn) { DirectedGraph dg=新的DirectedGraph(); ITrie-trie=null; 列表=新列表(); 尝试 { 使用(StreamReader sr=新StreamReader(fn)) { 字符串l; 而((l=sr.ReadLine())!=null) { dg.AddNode(l); 三.添加(l); 列表。添加(l); GetEdge(列表、trie、dg); } 返回dg; } }抓住 { 抛出新ArgumentException(); } }
我希望
StreamReader
将读取值添加到列表、
trie
和图形中的节点中
GetEdges()
是一个从给定列表中获取字符串并将边添加到图形数据结构的函数。

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

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