Is there any way to find the object name that caused the control to flow into the catch block from a NullReferenceException, so that we can easily debug by giving an alert or logging the object that was null?
-
I wish there were, but I've never seen anything. Not sure why it's not in modern debuggers, hopefully someone can elucidate. Best I can do is use lots of breakpoints, step through, narrow the scope down and the home in on the miscreant... – Alex Aug 08 '11 at 09:30
-
The best way is to prevent this kind of exceptions using [Guard Classes](http://ajdotnet.wordpress.com/2009/08/01/posting-guards-guard-classes-explained/) or [Code Contracts](http://research.microsoft.com/en-us/projects/contracts/). See [this](http://stackoverflow.com/questions/299439/net-guard-class-library) question for more details. – Paolo Moretti Aug 08 '11 at 09:37
-
3By definition, *no* object caused the exception... – Marc Gravell Aug 08 '11 at 09:55
3 Answers
No.
You only get the stack trace including line numbers.
This helps you in simple cases like this:
var result = myString.Trim();
But it doesn't help in lines like this:
var result = myObj.Method1().Method2();

- 171,043
- 40
- 335
- 443
(NOTE: The answer is for the original question, before it was edited four years after the fact)
What is an object's name? It's a design-time token to us, programmers, which identifies the object reference, but it has meaning only until compilation.
Some objects have a dedicated Name
property but that does not (and should not) have anything to do with the name of the object reference in code, it's the visual designer's courtesy to name object references after the Name property, but it's a convention rather than a requirement. Besides, a null reference cannot have Name property simply because the reference is null, it's not yet assigned to any object that has a readable Name.

- 4,933
- 1
- 28
- 59
-
You could have written just that first sentence and earned the secret 'Philosoprogrammer' badge ;) – Alex Aug 08 '11 at 09:56
-
1The point was not to philosophise on the identity :) but to show that it fundamentally cannot be done because the compiled code does not care for a name of a local var, it's just an object reference. – Boris B. Aug 08 '11 at 10:01
Well you can look at the stack trace, reflect the function, and display the parameters and have a guess based on stack state, but I'd say not really as the object could be anywhere in the function.

- 64,563
- 18
- 145
- 216