兔八哥极品软件园    运行: 4493天 | 文章:640 篇 | 评论:505 条 | 碎语:1条

c#自定义异常捕获机制,让程序漏洞无处可遁

作者:admin 发布于:2014-5-31 12:13 Saturday 分类:网络转载


在coding过程中工程师们(好吧,程序猿)免不了在值得小心翼翼的地方try catch一下,但在软件世界总免不了很多灵异事件,你不知道什么时候因为什么就给你崩溃一下,或许是代码本身确实有问题,或许是人品问题等等.

崩溃了怎么办,怎么处理.不妨给程序加一个全天候的异常捕获机制,让程序漏洞无处可遁吧!

public class CustomExceptionHandler
    {
        public CustomExceptionHandler()
        {
            Application.ThreadException += new ThreadExceptionEventHandler(this.OnThreadException);
        }
        private void OnThreadException(object sender, ThreadExceptionEventArgs args)
        {
            try
            {
                string errorMsg = "程序运行过程中发生错误,错误信息如下:\n";
                errorMsg += args.Exception.Message;
                errorMsg += "\n发生错误的程序集为:";
                errorMsg += args.Exception.Source;
                errorMsg += "\n发生错误的具体位置为:\n";
                errorMsg += args.Exception.StackTrace;
                writeLog(errorMsg);
                XtraMessageBox.Show("系统运行时发生未知错误!请重新启动系统", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            catch(Exception ex)
            {
                writeLog(ex.Message.ToString());
                XtraMessageBox.Show("系统运行时发生未知错误!请重新启动系统", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="str"></param>
        static void writeLog(string str)
        {
            if (!Directory.Exists("ErrLog"))
            {
                Directory.CreateDirectory("ErrLog");
            }

            using (StreamWriter sw = new StreamWriter(@"ErrLog\ErrLog.txt", true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                sw.WriteLine(str);
                sw.WriteLine("------------------------------------------------------------------------------------");
                sw.Close();
            }
        }

    }


Powered by 兔八哥极品软件 苏ICP备12049267号 sitemap