.Net下Unhandled Exception的捕获

本文介绍了如何在C#中处理未捕获的异常,包括线程异常和应用程序域异常。通过在Main()方法中注册事件处理器,可以捕获并记录这些异常,确保程序稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.\nExceptionType:{0}\nException Message: {1}\n StackTrace:{2}\n",
                     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};\nStackTrace:{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

转载于:https://www.cnblogs.com/gavin-king/p/4771748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值