Wrap every method in try-catch or specific part of code

前端 未结 5 950
星月不相逢
星月不相逢 2020-12-16 23:46

My senior colleague tells me to wrap every method within a try-catch block so they can trace where exceptions occurs to help debug issues quicker. Is it better to wrap every

5条回答
  •  一向
    一向 (楼主)
    2020-12-17 00:13

    Better to use it in critical parts of your code and then:

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        ServerForm form = new ServerForm();
        Application.Run(form);
    }
    static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.Message, Program.Name);
    }
    
    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        MessageBox.Show((e.ExceptionObject as Exception).Message, Program.Name);
    }
    

    just in case of unhandled Exception

提交回复
热议问题