Code throwing exception. Where is the error?

I'm learning C and C#, this question is for C#. I can't see where and what is throwing the exception. Any help much appreciated?

Here is the code:

    private static void geraNýjaNámsáætlun()
    {
        Console.Write("Hvada nám er þetta?:");
        String nám = Console.ReadLine();
        Console.Write("Villtu gera vikuáætlun? (y/n):");
        string answerYesOrNo = Console.ReadLine();
        answerYesOrNo.Trim();
        string path = @"C:\nám";
        if (answerYesOrNo.ToLower() == "y")
        {
            try
            {
                Console.Write("Enter the name you want for the filename:");
                string some = Console.ReadLine();
                string combined = Path.Combine(path, some + ".txt");
                if (File.Exists(combined))
                {
                    using (TextReader obj2 = new StreamReader(combined))
                    {
                        if (!obj2.ReadLine().Contains("Mon"))
                        {
                            obj2.Close();
                            TextWriter obj = File.AppendText(combined);
                            obj.WriteLine("Mon\t\t\t|Thue\t\t\t|Wedn\t\t\t|Thurs\t\t\t|Friday\t\t\t|Sat\t\t\t|Sun\t\t\t");
                            obj.Close();
                        }
                    }
                }
                using (TextWriter obj = File.AppendText(combined))
                {

                        Console.WriteLine("Enginn fyrir monday 3 fyrir thuesday 6 fyrir wednesday 9 fyrir thursday 12 fyrir friday 15 saturday 18 fyrir sunday");
                        Console.Write("Enter the number of tabs:");
                        int numberOfTabs = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Enter the class or lektion:");
                        string lektionOrClass = Console.ReadLine();
                        obj.WriteLine(Tabs(numberOfTabs) + "" + lektionOrClass);
                }

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

The exception throwing here

Now the exception thows here on this line, after I put a if check to see weather the ReadLine() is null. ? enter image description here

Jon Skeet
people
quotationmark

I can't immediately tell you where the problem is, but I can tell you how to find out.

First, remove this catch block (and indeed the try clause):

catch (Exception ex)
{
    System.Windows.Forms.MessageBox.Show(ex.Message);
}

That is hiding valuable information from you - in particular the stack trace. Two important points:

  • You should usually only catch exceptions which you believe you can actually handle, e.g. IOException due to an IO failure, which perhaps you can retry. NullReferenceException is always due to a bug (usually in your own code) and you shouldn't try to handle that other than potentially at a very high level for a service which just needs to continue working.
  • Whenever you log an exception, don't just log the message. Log the whole thing, including the stack trace and any nested exceptions. Otherwise you're losing huge amounts of helpful data which are used to pin down the problem.

Once you've stopped catching the exception and throwing away useful information, you'll see where the NullReferenceException is being thrown. At that point, you should be able to work out which null reference you're trying to dereference, and change the code appropriately.

If a single line is highlighted and you can't tell which reference might be null, that's often a symptom that you should refactor a complicated line of code into several simpler ones.

In fact, the problem may well be because you're reading from an empty file. In that case, obj2.ReadLine() will return a null value (indicating the end of the file) and when you try to dereference that with your Contains call, it will throw this exception. However, it's more important to understand the problem and how to diagnose it than to fix the immediate cause.

people

See more on this question at Stackoverflow