WinForm 未处理的异常 处理办法

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

错误提示 

按钮事件为:

  1. private void button1_Click(object sender, EventArgs e){  
  2.         throw new Exception();  

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

错误窗口

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

 

可以使用如下代码:

 static void Main()        
   
   Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
   AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
   Application.EnableVisualStyles();
   Application.Run(new Form1());
           
  static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)         
          
            //遇到未处理的异常不提示任何信息
   
  static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)         
          
            //遇到未处理的异常不提示任何信息     
       

 

 

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

运行结果

欢迎访问广告之家:http://www.adggs.com
原文地址:https://www.cnblogs.com/binlunia/p/11267744.html