0

I took over a legacy application and we are updating it piece by piece. However there are a few large blocks of code surrounded by a try catch.

When debugging on occasion we will get a null reference exception. The most generic "Object reference is not set to an instance of an object". This could be anything within 1000s of lines of legacy code.

Is there any possible way to get more detail on the line which this exception occured?

When surrounding in a try catch, the stack trace just points to the line that the exception block starts.

How can I get the exception to show me the exact line where it failed?

Terrance Jackson
  • 606
  • 3
  • 13
  • 40
  • 3
    use the debugger, and it should point to _exactly_ where things happen? what you're experiencing, i can only explain by something like `catch(Exception e){throw new Exception(e);}`. but if you can reliably recreate the exception and narrow it down to a try-block: set a breakpoint, step through it. – Franz Gleichmann Jun 02 '21 at 18:02
  • 1
    Does error message contain the line number? – jdweng Jun 02 '21 at 18:08
  • The exception that is thrown has a stack associated with it. If you do `var msg = someException.ToString()`, you'll see the stack in `msg`. – Flydog57 Jun 02 '21 at 18:20
  • From any catch block and using a short-circuit of the global exception handler and get the stack frame with filename, class name, method name and line number. https://www.google.com/search?c%23+global+exception+handler | https://www.google.com/search?q=c%23+get+stack+frame+filename+method+line+number –  Jun 02 '21 at 18:25
  • 1
    To get the exact line number and file name of the location that caused the null ref exception, make sure you deploy the .pdb files. PDB (program database) files include all this information and when deployed next to your .dll and .exe files, .NET will automatically include these details in the stack trace of an exception. Typically .pdb files are included in debug builds, but can be enabled in release builds by changing the project's properties. – Steven Jun 02 '21 at 19:04

1 Answers1

2

If you're just looking for the line number you can get it from Exception.StackTrace.

The StackTrace class represents a stack trace, which is an ordered collection of one or more stack frames

For example:

try
{
    throw new Exception();
}
catch (Exception exception)
{

    var stackTrace = new StackTrace(exception, true);
    var frame = stackTrace.GetFrame(0);
    var line = frame.GetFileLineNumber(); // now you've got the line
}

Also, you can use the call stack window while debugging which can help on debugging exceptions and on general debugging.

Ran Turner
  • 14,906
  • 5
  • 47
  • 53