winform攔截程式內未攔截到的例外狀況

C# – winform攔截程式內未攔截到的例外狀況

我的開發環境是用visual studio 2017

常常都有遇到有例外狀況卻沒有攔截到卻造成整個程式關閉或當掉的問題…,所以我在 Program.cs 這個檔案裏面增加了攔截未攔截到的例外狀況,我的作法是,當攔截到的時候,自動重新啟動以確保程式不是因為內部某些變數造成,並將錯誤訊息寫到LOG檔裡面

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_threadExceotion);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(currenDomain_UnhandledExceotion);

攔截的並執行的程式就是以下兩個副程式

  • Application_threadExceotion
  • currenDomain_UnhandledExceotion
攔截的並執行的程式就是以下兩個副程式
攔截的並執行的程式就是以下兩個副程式

範例程式碼…..

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test
{
	static class Program
	{
		/// 
		/// 應用程式的主要進入點。
		/// 
		[STAThread]
		static void Main()
		{
			Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
			Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_threadExceotion);
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(currenDomain_UnhandledExceotion);


			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new Form1());
		}
		static void Application_threadExceotion(object sender, System.Threading.ThreadExceptionEventArgs e)
		{

			Lg((e.Exception as Exception).Message);
			Thread.Sleep(5000);
			Process.Start(Environment.CurrentDirectory + @"\test.exe");
			Environment.Exit(Environment.ExitCode);
		}


		static void currenDomain_UnhandledExceotion(object sender, UnhandledExceptionEventArgs e)
		{
			Lg((e.ExceptionObject as Exception).Message);
			Thread.Sleep(5000);
			Process.Start(Environment.CurrentDirectory + @"\test.exe");
			Environment.Exit(Environment.ExitCode);

		}
		static void Lg(string message)
		{
			logClass LogClass = new logClass();
			LogClass.LogMessage(message);
		}
	}
	class logClass
	{
		public void LogMessage(string msg)
		{
			string sFilePath = Environment.CurrentDirectory + "\\Log_" + System.AppDomain.CurrentDomain.FriendlyName + ".txt";

			System.IO.StreamWriter sw = System.IO.File.AppendText(sFilePath);
			try
			{
				string logLine = System.String.Format(
					"{0:G}: {1}.", DateTime.Now, msg);
				sw.WriteLine(logLine);
			}
			finally
			{
				sw.Close();
			}
		}
	}
}

參考: https://dotblogs.com.tw/yc421206/archive/2010/07/12/16499.aspx