0

I am trying to a catch nullreference exception but I want to know the exact location (at which point or line I am getting that exception). I have one class named Employee and it has two properties: _Id and _Name.

static void Main(string[] args)
{
    Employee empobj = new Employee();

    try
    {
        empobj = null;
        //empobj._Id = empobj._Id.ToString();
        Console.WriteLine(empobj._Id);
        Console.WriteLine(empobj._Name);
        Console.ReadLine();
    }
    catch (NullReferenceException e)
    {
        Console.WriteLine("Exception caught: {0}", e.InnerException);
        Console.ReadLine();
    }
}
Abbas
  • 14,186
  • 6
  • 41
  • 72

3 Answers3

3

In visual studio go to Debug->Exceptions menu.

Exceptions dialog

Then select "Common Language Runtime Exceptions", Check the Thrown checkbox. This will break the execution when exception is thrown. You can find the breaked line is where exceptio is thrown.

In case of NullReferenceException you won't get much help about stacktrace, but this way you can get the cause easily.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
2

Look at the stack trace and it will have a break down of the execution tree, stating line numbers along with function names and so on. You can do this by debugging, outputting your exception stack trace to some medium, or by removing the try/catch and letting the exception halt execution of your application.

The key would be, though, to work around the exception so that it doesn't happen, if it's not an exceptional circumstance (i.e. if you expect that this is a scenario that could very well happen); so if your application can check, such as

if (thing != null) {
  var id = thing.Id;
  if (id != null) {
    var idText = id.ToString();
    // and so on
  }
} else {

} 

Where in the else, you either continue a different route, let the user retry or whatever.

If it is a truly exceptional circumstance (i.e. things should never be null) and the app can't do anything if it is, then let the exception happen, it breaks the application.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
2

Stack trace is the way to go, but the exception is coming from the following lines:

Console.WriteLine(empobj._Id);
Console.WriteLine(empobj._Name);

You are setting the employee object to null

empobj = null;

and then trying to access member variables from that class, which will no longer have values for these variables

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
Papaya21
  • 45
  • 6