Removing excessive try-catch blocks

前端 未结 8 2413
Happy的楠姐
Happy的楠姐 2021-02-14 19:10

I\'m refactoring a medium-sized WinForms application written by other developers and almost every method of every class is surrounded by a try-catch block. 99% of t

8条回答
  •  爱一瞬间的悲伤
    2021-02-14 19:34

    You should only handle only the exceptions that you are expecting, know how to handle and they are not corrupt the state of your application, otherwise let them throw.

    A good approach to follow is to log the exception first, then Restart your application, just like what Microsoft did when office or visual studio crashing. To do so you have to handle the application domain unhanded exception, so:

    AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException;
    
    //Add these two lines if you are using winforms
    Application.ThreadException += OnApplicationThreadException;
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    
    private void OnCurrentDomainUnhandledException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        //Log error
    
        //RestartTheApplication
    }
    

    Here an example on how to restart your application.

提交回复
热议问题