Get Null Object NullReferenceException

I have a problem with a huge solution at work that gets a lot of "Link to an object not installed on an object instance" errors. What is the best way to determine the null object (s) throwing an exception?

I can try to catch all of these exceptions in one place, but I cannot find a way to determine the member that is null, so I can fix it correctly.

try { } catch (Exception ex) { if (ex is ReferenceNullException) ex.?? } } 

Since I can view stacktrace, it would be prudent to think that you can also get what caused the error.

+6
source share
3 answers

Think about it for a second. This is a NullReferenceException. This means that you are trying to call a method or access a property of a NULL REFERENCE object. This means that the reference to the object you are trying to access is EMPTY, null. He does not exist.

What you are trying to find does not really exist.

Typically, a debugger is used to track a null reference to an object. Just set a breakpoint on the line that throws the exception, and check all the variables to see which one is zero.

The debugger is your best tool.

+10
source

If you cannot debug a NullReferenceException using the IDE in case this happens only from the client side or is difficult to reproduce, then NullReferenceException.StackTrace, which has FUNCTION / FILE / LINE information, will help you find the null object, NullReferenceException.ToString ( ) also include StackTrace, for example:

System.NullReferenceException: An object reference is not set to an object instance.

in WindowsFormsApplication3.Form1.button1_Click (object sender, EventArgs e) in D: \ VCS \ WindowsFormsApplication3 \ WindowsFormsApplication3 \ Form1.cs: line 26

To enable line number for release build, pls check this box Display line numbers in Stack Trace for .NET build in release mode

+3
source

Check out the Try-Catch documentation http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.71).aspx

You may have several catches in try catch to handle various exceptions in your own way.

 try{ //do stuff } Catch (NullReferenceException ex){ } Catch (Exception ex) { } 
0
source

Source: https://habr.com/ru/post/923876/


All Articles