C#程序异常关闭时的捕获
本文主要以一个简单的小例子,描述C#Winform程序异常关闭时,如何进行捕获,并记录日志。
概述
有时在界面的事件中,明明有try...catch进行捕获异常,但是还是会有异常关闭的情况,所以在程序中如何最终的记录一些无法捕获的异常,会大大方便问题的定位分析及程序优化。
涉及知识点
以下两个异常事件,主要应用不同的场景。
- Application.ThreadException在发生应用程序UI主线程中未捕获线程异常时发生,触发的事件。
- AppDomain.CurrentDomain.UnhandledException当后台线程中某个异常未被捕获时触发。
源代码
主要程序(Program):
usingSystem; usingSystem.Collections.Generic; usingSystem.IO; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; namespaceDemoException { staticclassProgram { //////应用程序的主入口点。 /// [STAThread] staticvoidMain() { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.ThreadException+=newSystem.Threading.ThreadExceptionEventHandler(Application_ThreadException); //处理非线程异常 AppDomain.CurrentDomain.UnhandledException+=newUnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(newFrmMain()); glExitApp=true;//标志应用程序可以退出 } //////是否退出应用程序 /// staticboolglExitApp=false; //////处理未捕获异常 /// ////// privatestaticvoidCurrentDomain_UnhandledException(objectsender,UnhandledExceptionEventArgse) { SaveLog("-----------------------begin--------------------------"); SaveLog("CurrentDomain_UnhandledException"+DateTime.Now.ToString("yyyy-MM-ddhh:mm:ss")); SaveLog("IsTerminating:"+e.IsTerminating.ToString()); SaveLog(e.ExceptionObject.ToString()); SaveLog("-----------------------end----------------------------"); while(true) {//循环处理,否则应用程序将会退出 if(glExitApp) {//标志应用程序可以退出,否则程序退出后,进程仍然在运行 SaveLog("ExitApp"); return; } System.Threading.Thread.Sleep(2*1000); }; } /// ///处理UI主线程异常 /// ////// privatestaticvoidApplication_ThreadException(objectsender,System.Threading.ThreadExceptionEventArgse) { SaveLog("-----------------------begin--------------------------"); SaveLog("Application_ThreadException:"+e.Exception.Message); SaveLog(e.Exception.StackTrace); SaveLog("-----------------------end----------------------------"); } publicstaticvoidSaveLog(stringlog) { stringfilePath=AppDomain.CurrentDomain.BaseDirectory+@"\objPerson.txt"; //采用using关键字,会自动释放 using(FileStreamfs=newFileStream(filePath,FileMode.Append)) { using(StreamWritersw=newStreamWriter(fs,Encoding.Default)) { sw.WriteLine(log); } } } } }
出错的程序:
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Threading; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; namespaceDemoException { publicpartialclassFrmMain:Form { publicFrmMain() { InitializeComponent(); } privatevoidFrmMain_Load(objectsender,EventArgse) { } privatevoidbtnTestUI_Click(objectsender,EventArgse) { inta=0; intc=10/a; } privatevoidbtnTest2_Click(objectsender,EventArgse) { Threadt=newThread(newThreadStart(()=> { inta=0; intc=10/a; })); t.IsBackground=true; t.Start(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。