Why doesn't calling the calling event handler throw an exception?

After reading this question , it seems that 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 fine (and does nothing). How does this code behave 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: Catch this exception, according to Lasse W. Carlsen:

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

The problem is that the Load event is catching your exception.

There are other questions about this and other posts on the network about this:

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

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

In short 2: The code does indeed throw a null reference exception, as you expected, you just don't see it

+6
source

How do you determine if this code is working fine? It is very likely that this code throws an exception under the hood, which is then swallowed by the Windows Forms runtime code. There are several reasons why this swallowing of exceptions could be handled by silent debugger / runtime

I would try debugging this or the code or Messagebox.Show installation of the Messagebox.Show line only under the delegate call and see if it will be executed.

+2
source

Are you sure the code is not doing anything?

I get a NullReferenceException when I try to do this:

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

Perhaps your code never executes (for example, your Form1_Load event Form1_Load not called), or maybe your exception is swallowed (for example, by another thread)?

0
source

All Articles