Best Practice for Exception Handling in a Windows Forms Application?

前端 未结 16 2063
滥情空心
滥情空心 2020-11-29 14:20

I\'m currently in the process of writing my first Windows Forms application. I\'ve read a few C# books now so I\'ve got a relatively good understanding of what language feat

16条回答
  •  醉酒成梦
    2020-11-29 15:04

    you can trap the ThreadException event.

    1. Select a Windows Application project in Solution Explorer.

    2. Open the generated Program.cs file by double-clicking on it.

    3. Add the following line of code to the top of the code file:

      using System.Threading;
      
    4. In the Main() method, add the following as the first line of the method:

      Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
      
    5. Add the following below the Main() method:

      static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
      {
          // Do logging or whatever here
          Application.Exit();
      }
      
    6. Add code to handle the unhandled exception within the event handler. Any exception that is not handled anywhere else in the application is handled by the above code. Most commonly, this code should log the error and display a message to the user.

    refrence: https://blogs.msmvps.com/deborahk/global-exception-handler-winforms/

提交回复
热议问题