• .Net下Unhandled Exception的捕获


    C# 处理unhandled Exception方式如下:
    1.    在程序的Main()方法中增加如下代码。
          //处理线程未处理的异常
       Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
       //处理系统未处理的异常
       AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
          //运行程序
       Application.Run(new frmServerMain());
       
    2.    方法:
            static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
            {
                string str = "";
                Exception error = e.Exception as Exception;
                if (error != null)
                {
                    str = string.Format("Application unhandled exception. ExceptionType:{0} Exception Message: {1} StackTrace:{2} ",
                         error.GetType().Name, error.Message, error.StackTrace);
                }
                else
                {
                    str = string.Format("Application Thread Exception Msg:{0}", e);
                }
                WriteErrInfo(str);
            }

            static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            {

                string str = "";

                Exception error = e.ExceptionObject as Exception;
                if (error != null)
                {
                    str = string.Format("Application UnhandledException:{0}; StackTrace:{1}", error.Message, error.StackTrace);
                }
                else
                {
                    str = string.Format("Application UnhandledError:{0}", e);
                }
                WriteErrInfo(str);
            }

            static void WriteErrInfo(string vErrMsg)
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(Application.StartupPath + "\Log\TestException.log",
                    System.IO.FileMode.Append, System.IO.FileAccess.Write))
                {
                    using (System.IO.StreamWriter w = new System.IO.StreamWriter(fs,System.Text.Encoding.UTF8))
                    {
                        w.WriteLine(vErrMsg); DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                    }
                }
            }

    详细分析可参见:

    http://www.cnblogs.com/eaglet/archive/2009/02/17/1392191.html


    Impossible = I'm possible
    Don't be the same, be better. Just do it.
    You'll be there.
  • 相关阅读:
    HDU 6214 Smallest Minimum Cut 最小割,权值编码
    HDU 6196 happy happy happy 爆搜加剪枝
    2017 ACM-ICPC 亚洲区(西安赛区)网络赛 Coin 概率+矩阵快速幂
    HDU 6199 2017沈阳网络赛 DP
    HDU 6200 2017沈阳网络赛 树上区间更新,求和
    HDU 6203 2017沈阳网络赛 LCA,DFS+树状数组
    docker平时使用异常记录
    AI模型运维——NVIDIA驱动、cuda、cudnn、nccl安装
    python——平时遇到问题记录
    python——虚拟环境管理大合集
  • 原文地址:https://www.cnblogs.com/gavin-king/p/4771748.html
Copyright © 2020-2023  润新知