. Net WinForm has its own unhandled exception mechanism. The code inside the WinForm creates a large try...catch for the message loop within the Applicatin.run method. Thus, any exception in the main thread of the GUI will be captured by this try...catch, the default unhandled exception handler will extract all the information of the exception and then appear in an error dialog box, then the program is aborted. So my try...catch will not work, that is, the following code to catch the exception is invalid. static void Main ()
{
Try
{
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
Application.Run (New MainFrm ());
}
catch (Exception e)
{
Messgaebox.show (E.message);
}
}
for this problem, you can handle the application.threadexception exception so that you can intercept the exception inside the main thread of the 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 are shutting down.");
Environment.exit (1); Shutting down
}
The above state is the result of debugging after compiling to EXE, which is different in the IDE environment.
Handling Application.ThreadException exceptions, blocking exceptions to the main thread of the GUI