Winform 全局异常捕获处理

我们在开发winform程序的时候经常需要处理异常,如果没处理好异常程序就会崩溃,影响用户体验。
所以防止程序在没处理到异常时能由一个全局的异常捕获处理,在winform的program文件里面我们可以添加全局异常捕获事件,然后处理异常。

在program的main方法里面设置异常处理方式,然后注册异常处理的两个事件:

1.设置异常处理方式

//处理未捕获的异常
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

image.png

2.ThreadException 处理UI线程异常

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

Application_ThreadException方法:

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = "";
            string strDateInfo = "\r\n\r\n出现应用程序未处理的异常:" + DateTime.Now.ToString() + "\r\n";
            Exception error = e.Exception as Exception;
            if (error != null)
            {
                string logInfo = string.Format(strDateInfo + "异常类型:{0}\r\n异常消息:{1}\r\n异常信息:{2}\r\n", error.GetType().Name, error.Message, error.StackTrace);
                str = string.Format(strDateInfo + "异常类型:{0}\r\n异常消息:{1}\r\n",
                error.GetType().Name, error.Message);
            }
            else
            {
                str = string.Format("应用程序线程错误:{0}", e);
            }

            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

3.UnhandledException 处理非UI线程异常

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

CurrentDomain_UnhandledException 方法:

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = "";
            Exception error = e.ExceptionObject as Exception;
            string strDateInfo = "出现应用程序未处理的异常:" + DateTime.Now.ToString() + "\r\n";
            if (error != null)
            {
                string logInfo = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}", error.Message, error.StackTrace);
                str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r", error.Message);
            }
            else
            {
                str = string.Format("Application UnhandledError:{0}", e);
            }

            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
posted @ 2021-10-12 11:31  XSpringSun  阅读(482)  评论(0编辑  收藏  举报