-1

I have a function to create a graph and add some values to a few other data structures using a StreamReader to read in lines from a .txt file.

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();
    }
}

I expect the StreamReader to add the read values to a list, trie and nodes in a graph. GetEdges() is a function that gets strings from the given list and adds edges to the graph data structure.

FlutterDashie
  • 108
  • 14
Jared
  • 11
  • 2
  • 6
    Welcome to Stack Overflow. Why are you throwing an `ArgumentException` if *anything* goes wrong? I'd strongly suggest removing the try/catch block - it'll make it a lot easier to work out what's wrong if you let the original exception propagate. – Jon Skeet May 03 '19 at 19:48
  • 2
    Note that while `trie` is `null`, `trie.Add(l)` will throw `NullReferenceException`, aside from anything else. – Jon Skeet May 03 '19 at 19:48
  • 1
    You never set `trie` to anything... – Rufus L May 03 '19 at 19:50
  • 1
    Yup, you're getting a `NullReferenceException`, but because of how you wrote your exception handler, you'd never know it. Why are you catching exceptions just to throw an unrelated, blank, exception? –  May 03 '19 at 20:03
  • Welcome to Stack Overflow! Putting any potentially questionable code practices aside, congratulations on having a well-formatted, well-written question! We love to see things like that. – FlutterDashie May 03 '19 at 20:06

1 Answers1

0

As @JonSkeet and @RufusL have pointed out, trie is instantiated as null, and as it is never set to anything, it is still null when trie.Add(l); is called. This throws a NullReferenceException, but because of the try/catch block, that exception is caught, its data is ignored, and instead an ArgumentException with default values is thrown in its place. I would highly recommend having some way of throwing or getting data from the original exception for debugging purposes.

FlutterDashie
  • 108
  • 14