UnhandledException

static class Program
    {
        
/// <summary>
        
/// The main entry point for the application.
        
/// </summary>
        [STAThread]
        
static void Main()
        {
            
//异常捕捉
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException 
+= new ThreadExceptionEventHandler(UIThreadException);
            AppDomain.CurrentDomain.UnhandledException 
+= new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            
            
//正常程序运行处
            Application.EnableVisualStyles();  Application.SetCompatibleTextRenderingDefault(false);  Application.Run(new AutoJudge());
        }
        
/// <summary>
        
/// 线程异常捕捉
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="t"></param>
        private static void UIThreadException(object sender, ThreadExceptionEventArgs t)
        {
            
try
            {
                
string errorMsg = "Windows窗体线程异常:";
                MessageBox.Show(errorMsg 
+ t.Exception.Message + Environment.NewLine + t.Exception.StackTrace);
            }
            
catch
            {
                MessageBox.Show(
"不可恢复的Windows窗体异常,应用程序将退出!");
            }
        }
        
/// <summary>
        
/// 非线程异常捕捉
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            
try
            {
                Exception ex 
= (Exception)e.ExceptionObject;
                
string errorMsg = "非Windows窗体线程异常:";
                MessageBox.Show(errorMsg 
+ ex.Message + Environment.NewLine + ex.StackTrace);
            }
            
catch
            {
                MessageBox.Show(
"不可恢复的非Windows窗体线程异常,应用程序将退出!");
            }
        }
    }
原文地址:https://www.cnblogs.com/zhangpengshou/p/1982287.html