简体   繁体   中英

Why doesn't calling a null event handler raise an exception?

After reading this question , it seems like the following code should fail:

private void Form1_Load(object sender, EventArgs e)
{
   EventHandler myHandler = null;
   myHandler(this, null);
}

But when I run it, it works just fine (and does nothing). How does that code behave any differently than the following?

private void Form1_Load(object sender, EventArgs e)
{
   EventHandler myHandler = null;
   EventHandler myCopy = myHandler;
   if (myCopy != null)
   {
      myHandler(this, null);
   }
}

Edit: Catching the exception this way works, according to Lasse V. Karlsen's answer:

private void Form1_Load(object sender, EventArgs e)
{
   try
   {
      EventHandler myHandler = null;
      myHandler(this, null);
   }
   catch (Exception ex)
   {
      this.Text = "Exception!";
   }
}

The problem here is that the Load event is swallowing your exception.

There are other questions here on SO about this and other posts on the net about it:

In short, in certain circumstances (the most often cited reason is a 32-bit .NET program running on 64-bit Windows) any exceptions in the Load event of a WinForms Form will be swallowed.

You can wrap the Form Load event in a try/catch block to catch it, and determine how to react to it.

In short 2: The code does indeed cause a null reference exception as you expected, you're just not seeing it

How are you determining that this code runs just fine? It's very likely that this code is throwing an exception under the hood which is just then swallowed by the Windows Forms Runtime code. There are several reasons why this exception swallowing could be handled silently by the debugger / runtime

I would try debugging this or code or barring that put a Messagebox.Show line just under the delegate invoke and see if it executes.

Are you sure the code does nothing ?

I do get a NullReferenceException when I try this:

class Program
{
    static void Main(string[] args)
    {
        EventHandler myhandler = null;
        myhandler(null, null);
    }
}

Maybe your code is never executed (eg your Form1_Load event handler is not called), or maybe your exception is swallowed (eg by a different thread)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM