標籤:winform style color io os ar for div sp
.Net Winform有著自己的未處理異常機制。 Winform內部的代碼會在Applicatin.Run方法裡面為訊息迴圈建立一個大的try...catch。 這樣, 任何在GUI主線程裡面的異常都會被這個try...catch所捕捉到, 這個預設的未處理異常handler會提取異常的所有資訊然後顯示在一個錯誤對話方塊裡面,接著程式就中止了。這樣我的try...catch就沒有作用了,即下面的捕捉異常的代碼是無效的。static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainfrm());
}
catch(Exception e)
{
MessgaeBox.Show(e.Message);
}
}
對於這個問題,可以處理Application.ThreadException異常,這樣就可以攔截GUI主線程裡面的異常了:
static void Main()
{
//// Setup unhandled exception handlers
//AppDomain.CurrentDomain.UnhandledException += // CLR
// new UnhandledExceptionEventHandler(OnUnhandledException);
Application.ThreadException += // Windows Forms
new System.Threading.ThreadExceptionEventHandler(
OnGuiUnhandedException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
//// CLR unhandled exception
//private static void OnUnhandledException(Object sender,
// UnhandledExceptionEventArgs e)
//{
// HandleUnhandledException(e.ExceptionObject);
//}
// Windows Forms unhandled exception
private static void OnGuiUnhandedException(Object sender,
ThreadExceptionEventArgs e)
{
HandleUnhandledException(e.Exception);
}
static void HandleUnhandledException(Object o)
{
Exception e = o as Exception;
if (e != null)
{ // Report System.Exception info
MessageBox.Show("Exception = " + e.GetType());
MessageBox.Show("Message = " + e.Message);
MessageBox.Show("FullText = " + e.ToString());
}
else
{ // Report exception Object info
MessageBox.Show("Exception = " + o.GetType());
MessageBox.Show("FullText = " + o.ToString());
}
MessageBox.Show("An unhandled exception occurred " +
"and the application is shutting down.");
Environment.Exit(1); // Shutting down
}
上述狀態是編譯成EXE後調試的結果,在IDE環境中情況不同。
處理Application.ThreadException異常, 攔截GUI主線程的異常