【发布时间】: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 块 - 如果您让原始异常传播,它将更容易找出问题所在。 -
请注意,虽然
trie是null,但trie.Add(l)将抛出NullReferenceException,除此之外。 -
你从来没有将
trie设置为任何东西...... -
是的,你得到了一个
NullReferenceException,但由于你编写异常处理程序的方式,你永远不会知道它。为什么你捕获异常只是为了抛出一个不相关的空白异常? -
欢迎来到 Stack Overflow!把任何可能有问题的代码实践放在一边,恭喜你有一个格式良好、编写良好的问题!我们喜欢看到这样的事情。
标签: c# argumentexception