0

I need a suggestion regarding Object reference issue. I got this message ExceptionMessage: Object reference not set to an instance of an object. (because some null object) I am printing the stack trace when an error occurs:

 Exception systemException = lastError.GetBaseException();

By using ex.Message I am able to get the method where exception has occurred but I am not getting any information regarding the line (of that method) where exception occurred. I need to know at which line object reference has occurred and which object was null when this exception came.

Rocky Singh
  • 15,128
  • 29
  • 99
  • 146

3 Answers3

4

You need the actual stacktrace:

systemException.StackTrace

If you want the line numbers, you will need to do something like this:

StackTrace st = new StackTrace(systemException, true);
StackFrame[] frames = st.GetFrames();

foreach(StackFrame frame in frames)
    frame.GetFileLineNumber();
EkoostikMartin
  • 6,831
  • 2
  • 33
  • 62
0

That line number is pretty much guaranteed to be in the stack trace. If you want to drill down on it, put a try-catch in the large block of code where it might be happening and drop a breakpoint on the catch block, which will allow you to drop down through the InnerExceptions inside of visual studio (if any exist).

tmesser
  • 7,558
  • 2
  • 26
  • 38
0

Maybe this helps

class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string a = null;
                a.ToString();
            }
            catch (Exception ex)
            {
                var s = ex.StackTrace;
                Console.WriteLine(ex.Source);
                int st = s.LastIndexOf("line");
                Console.WriteLine(s.Substring(st, s.Length - st));
            }
        }
    }

Edited :

And yes I just learned, using StrackTrace in the answer posted by EkoostikMartin. I think it is a better answer.

Dinesh
  • 3,652
  • 2
  • 25
  • 35