简体   繁体   中英

Global Exception Handler implementation C# WinForms

Im trying to implement a global "try catch block" and keep my app running after handling any:

public class GlobalExceptionHandler
{
    public GlobalExceptionHandler()
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    }
    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        try
        {
            throw (e.ExceptionObject as Exception);
        }
        catch (Exception ex)
        {
        }
    }
}

Problems:

  1. I expected to handle all exceptions in a familiar way with a try catch block. Am i doing smth wrong by rethrowing them to catch?
  2. The code above still drops the app with an exception popup in the place exception was originally thrown like it has not been handled.
  3. Guess my approach is a complete fail from the start. I wanted to avoid using a lot of try catch blocks through the whole app and decided to localize all exceptions handling. How good this idea is? Should i find a better way to implement a global handler or stick to dozens of try catch blocks?

windows forms have separate event for handling exceptions on GUI thread (ie exceptions which occur on GUI events like button click, textbox text change, etc..):

Application.ThreadException += new ThreadExceptionEventHandler(Handler);
    
public void Handler(object sender, ThreadExceptionEventArgs t)
{
        //exceptions handling code here...
        

        // you can throw exception at the end of method if you want this exception to go unhandled, not writing throw will swallow exception
        /// throw t.Exception
}

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