程序的异常处理及输出本地日志

场景:需要发一个产品,为了提高产品的可用性及用户在操作过程中不会有过多的地方出现程序崩溃问题,我们可以把在程序中抓到异常写到本地的文件里面,便于我们查找问题。

使用方法:其实只是用了一些很常见的东西的组合,

1.在你认为可能会有异常地方加上异常捕捉的代码:

try
{
     //需要正常被执行的代码
}
catch(Exception ex)
{
     //不要把异常抛出去
    //throw ex;
     //你可以这样
    Trace.WriteLine("方法名:"+ex.Message);
}

2. 为你的程序添加 文件的跟踪和调试的接收者:TextWriterTraceListener

3. 对于一些我们无法预料到的异常问题,我们可以用这两个事件来获取:Application.ThreadException 和 AppDomain.CurrentDomain.UnhandledException

整体代码如下(Program.cs中):

//这个是Main函数中的代码:
            InitLog();
            Trace.WriteLine("APP Strart:" + string.Format("{0}{1}", Application.ProductName, Application.ProductVersion));
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            form = new Form1();
            Application.Run(form);
            Trace.Flush();

InitLog方法及异常捕捉事件的委托:

        private static void InitLog()
        {
            string path = Path.ChangeExtension(Application.ExecutablePath, ".log");
            if (File.Exists(path))
            {
                try
                {
                    FileInfo file = new FileInfo(path);
                    if (file.Length > 3 * 1024 * 1024)
                    {
                        File.Delete(path);
                    }
                }
                catch
                {
                }
            }
            TextWriterTraceListener listener = new TextWriterTraceListener(path);
            listener.TraceOutputOptions |= TraceOptions.DateTime;
            Trace.Listeners.Add(listener);
        }

这里我是把捕获到的异常写到了本地的日志中,而且以消息框的形式显示了出来:

       //这里form就是当前的主窗体    定义:private static Form1 form; 
       private delegate void ShowExHandler(object exObj);

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Trace.WriteLine("CurrentDomain_UnhandledException:");
            Exception ex = e.ExceptionObject as Exception;
            Trace.WriteLine(ex.Message);
            Trace.Flush();
            if (form != null && !form.IsDisposed)
            {
                form.BeginInvoke(new ShowExHandler(ShowException), e.ExceptionObject);
            }
        }


        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            Trace.WriteLine("Application_ThreadException:");
            Trace.WriteLine(e.Exception.Message);
            Trace.Flush();
            if (form != null && !form.IsDisposed)
            {
                form.BeginInvoke(new ShowExHandler(ShowException), e.Exception);
            }
        }

        static void ShowException(object exObject)
        {
            Exception ex = exObject as Exception;
            if (ex != null)
            {
                form.Invoke(new MethodInvoker(delegate() { MessageBox.Show(form, ex.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Error); }));
            }
        }
原文地址:https://www.cnblogs.com/yuqf/p/3066516.html