C# Source Code: Defining a Global Exception Handler for a Windows Form Application
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Defining a Global Exception Handler for a Windows Form Application
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Saturday, April 10, 2004
Hits:
837
Category:
Windows Forms/GUI/Controls
Article:
To capture any an handled exceptions in a WinForm Application use the following code: // Turn on global exception handler. Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnThreadException); // Turn off global exception handler (will revert back to the default handler). Application.ThreadException -= new System.Threading.ThreadExceptionEventHandler(OnThreadException); //Callback for thread exceptions internal void OnThreadException(object sender ,System.Threading.ThreadExceptionEventArgs t) { // Add code here to log the error, show a messagebox, send an e-mail etc // Note, if an error occurs in this routine you will see the JIT debugging, // NOT the Windows Forms handler. eg, throw new ArgumentException("Ohhh no another mistake!!!") string strMsg; Exception exp = t.Exception; strMsg = string.Format("We're sorry, an untrapped error occurred.{0}The error message was:{0}{1}", Environment.NewLine, exp.Message); MessageBox.Show(strMsg, "Global Exception Trap", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // Check the different exception types if (exp is ApplicationException) { //Application exception } else if (exp is SystemException) { //System exception } else { //Catch other exception types here } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet