首页 > 代码库 > 处理Application.ThreadException异常, 拦截GUI主线程的异常
处理Application.ThreadException异常, 拦截GUI主线程的异常
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainfrm());
}
catch(Exception e)
{
MessgaeBox.Show(e.Message);
}
}
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主线程的异常