1

I have an application (released) and a NullReferenceException that is popping up for users VERY rarely, yet I want to take care of it. I've looked over the stack and methods in it and can find no specific location where it would occur (it is a fairly large method/algorithm). For now I will just be surrounding the call itself with a try/catch but would like to handle it better IF I can figure out the case.
Problem is, as far as I can tell, a NRE provides no clue as to what specifically in the code caused it. Is there a way to even get line numbers or any other information that could hint at the cause?

Broots Waymb
  • 4,713
  • 3
  • 28
  • 51

1 Answers1

2

A few tips:

  1. If you deploy your symbols file (.pdb) alongside your executable/dll files, then the stack traces you get will include line numbers.
  2. It can also help to break your method down into smaller pieces so that your stack trace gives you a better idea of where you were when the error happened.
  3. You can begin each method by checking its inputs for null or otherwise invalid values, so you fail fast with a meaningful message.

    private void DoSomething(int thingId, string value)
    {
        if(thingId <= 0) throw new ArgumentOutOfRangeException("thingId", thingId);
        if(value == null) throw new ArgumentNullException("value");
        ...
    }
    
  4. You can surround each method with an exception wrapper to provide more information at each level of the stack trace on its way up.

    private void DoSomething(int thingId, string value)
    {
        try
        {
            ...
        }
        catch (Exception e)
        {
            throw new Exception("Failed to Do Something with arguments " +
                new {thingId, value},
                e); // remember to include the original exception as an inner exception
        }
    }
    
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315