• 如何处理Windows Forms程序中未处理的异常


    如果Windows Forms程序中有未被捕获的异常,会导致程序崩溃并且给用户造成不良的印象。例如下面的程序,模拟了一个未捕获的异常:

    clip_image002
    按钮事件为:

    private void button1_Click(object sender, EventArgs e)
    {
            throw new Exception();
    }

    点击Exception 按钮,会弹出如下默认窗口

    clip_image004

    Windows Forms提供了两个事件来处理未捕获的异常发生时的情况,分别是 Application.ThreadException和AppDomain.UnhandledException事件,前者用来处理UI线程中的异常,后者处理其他线程中的异常。要使程序使用自定义的事件来处理异常,可以使用如下代码:

    static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }        
    
            static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            {
                MessageBox.Show("抱歉,您的操作没有能够完成,请再试一次或者联系软件提供商");
                LogUnhandledException(e.ExceptionObject);
            }
    
            static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
            {
                MessageBox.Show("抱歉,您的操作没有能够完成,请再试一次或者联系软件提供商");
                LogUnhandledException(e.Exception);
            }
    
            static void LogUnhandledException(object exceptionobj)
            {
                //Log the exception here or report it to developer
            }
        }

    此时运行该程序的结果如下:

    clip_image006

  • 相关阅读:
    解决javaScript在不同时区new Date()显示值不同问题
    页面返回上一页浏览位置
    如何disabled禁用所有表单input输入框元素
    js根据json数组多个字段排序
    No identifier specified for entity
    Android resource compilation failed
    android 系统dialog的应用
    android消息处理源码分析
    Linux下常用命令
    ContentProvider和ContentResolver的使用
  • 原文地址:https://www.cnblogs.com/yinzixin/p/1631633.html
Copyright © 2020-2023  润新知