Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!";
   }
}
like image 607
jtpereyda Avatar asked Feb 18 '23 07:02

jtpereyda


1 Answers

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

like image 123
Lasse V. Karlsen Avatar answered Mar 06 '23 20:03

Lasse V. Karlsen