现在的位置: 首页 > 综合 > 正文

c# 异常句柄

2012年02月28日 ⁄ 综合 ⁄ 共 2076字 ⁄ 字号 评论关闭

c# 异常句柄 好象以前写过,再写一次.

 

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace ttt
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // Add the event handler for handling UI thread exceptions to the event.     
            Application.ThreadException += new ThreadExceptionEventHandler(Form_UIThreadException);

            // Set the unhandled exception mode to force all Windows Forms errors to go through     
            // our handler.     
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // Add the event handler for handling non-UI thread exceptions to the event.      
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);   

            //--------------------------------------------------

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form_main());
        }//

        // Handle the UI exceptions by showing a dialog box, and asking the user whether     
        // or not they wish to abort execution.     
        private static void Form_UIThreadException(object sender, ThreadExceptionEventArgs t)
        {
            MessageBox.Show("异常句柄 1:" + t.Exception.ToString());
        }//

        // Handle the UI exceptions by showing a dialog box, and asking the user whether     
        // or not they wish to abort execution.     
        // NOTE: This exception cannot be kept from terminating the application - it can only      
        // log the event, and inform the user about it.  
        //这个是没法阻止程序退出的,只能做记录
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //e.IsTerminating;//这个属性告诉我们这个异常是否会导致应用终止

            Exception ex = (Exception)e.ExceptionObject;
            string errorMsg = "An application error occurred. Please contact the adminstrator " +
            "with the following information:\n\n";
            errorMsg += ex.Message + "\n\nStack Trace:\n" + ex.StackTrace;

            MessageBox.Show("异常句柄 2:" + errorMsg);
        }//

    }//
}//

抱歉!评论已关闭.