Handling exceptions in .NET (GUI) event functions

2019-07-18 14:15发布

问题:

Note: I don't do .NET programming regularly. Normally I do native/MFC, so I'm a bit lost as how to do this properly in the context of C#.

We're displaying .NET control in the context of a native MFC application. That means the GUI thread is a native thread calling into the WndProc of the .NET control. (Well, at least as far as I can tell.)

Obviously, we do not want to throw exceptions from our (GUI) event handlers, as there is no proper handler down the call stack that would catch them.

As far as I can tell, the solution(s) with AppDomain / UnhandledExceptionEventHandler do not make sense in a native MFC application. (Please correct me if I'm wrong.)

So back to the question: How can I avoid having to add a try/catch block to each event handler of the C# control code? Is there some place (System.Forms...Control.WndProc maybe?) where I can catch all .NET exceptions and just display an error dialog to the user?

回答1:

You can reduce boilerplate code by using a functional approach. Write a function like this:

public class Util
{
    public static void SafeCall(Action handler)
    {
      try
      {
           handler();
      }
      catch(Exception ex)
      {
         // process ex here
      }
}

And reuse it in every of your GUI event handlers:

void MyEvent(object sender, EventArgs e)
{
    Util.SafeCall(()=>NameOfYourHandlerMethod(sender,e));
};

or

void MyEvent(object sender, EventArgs e)
{
    Util.SafeCall(
    delegate
    {
      // enter code here
    });
};

This might need some additional work to get the sender/EventArgs parameters the way you want them, but you should get the idea.