NullReferenceException is not always thrown when it should be

I noticed an oddity in the development of my C # application with Visual Studio 2010. In some cases, a NullReferenceException is not thrown if, as far as I know, it should. Instead, the application continues as usual, but gets stuck so that I cannot close it normally and I have to kill it.

Consider the following as an example:

public class MyControl : UserControl
{
    private SomeClass myObj;
    public MyControl()
    {
        Bar();
        myObj = new SomeClass();
    }

    public void Bar()
    {
        myObj.SomeProperty = 5; // myObj is null here but no exception gets thrown
    }
}

      

Instead of a runtime exception, the myObj.SomeProperty = 5;

code jumps out of the function back to where the constructor for MyControl

is called by the parent form. I can get NullReferenceExceptions (as well as other exceptions) caught by the debugger in other instances, just not like this.

Should a NullReferenceException be thrown or am I misunderstanding something about C # and / or .NET?

+3


source to share


2 answers


In VS go to Debug-> Exceptions-> Common Language Runtime Exceptions and check the Throw checkbox then try again. It will show you if there is an exception caught somewhere else.



+2


source


Cause

Somewhere along the call stack, a try / catch block terminates this exception and handles it gracefully.

How to view handled exceptions

If you really want to check if an exception is thrown, regardless of whether it is executed without handling, you need to enable the Thrown

exception checkbox for Common Language Runtime Exceptions

in the Debug > Exceptions...

menu section .



Repeat

Turn on the Thrown Exception option, try again and you will receive an exception notification.

Other possibilities

Your code may be outdated.

+3


source







All Articles