Welcome to MSDN Blogs Sign in | Join | Help

SYSK 163: New Way to Reduce the Number of Unhandled Exceptions

Except for ThreadAbortException and AppDomainUnloadedException exceptions, all other unhandled exceptions in .NET 2.0 lead to process termination.  Note: this was not the case in earlier version of .NET – e.g. unhandled exceptions that happen on a thread from a thread pool would not terminate the process.  As a temporary compatibility measure, you can revert to the old behavior by adding <legacyUnhandledExceptionPolicy enabled="1"/> to the <runtime> element of the configuration file.  See http://msdn2.microsoft.com/en-us/library/ms228965.aspx for more information.

 

.NET 2.0 WinForms class library has a new method SetUnhandledExceptionMode that tells the runtime to throw (or not) Application.ThreadException in case an unhandled exception happens on either the application main thread or on other threads.  In essence, this gives you a chance to always catch an unhandled exception and decide what to do with it, instead of letting the runtime terminate the application…

 

Consider the following code:

 

static void Main()

{

// Add the event handler for handling UI thread exceptions to the event.

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(YourHandlerFunctionHere);

 

// Set the unhandled exception mode to force all Windows Forms errors to go through

// our handler.

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

 

// Add the event handler for handling non-UI thread exceptions to the event.

AppDomain.CurrentDomain.UnhandledException +=

    new UnhandledExceptionEventHandler(YourHandlerFunctionHere);

 

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new Form1());

}

 

Now, if an unhandled exception occurs, your handler will be invoked where you can, perhaps, display the message to the user and let the user decide whether to terminate the application or ignore the exception and continue running.  I also strongly recommend to log the exception with the detailed stack trace info, so it’ll be easier for developers to get to the bottom of the problem…

 

For more information, visit http://msdn2.microsoft.com/en-us/library/ms223898.aspx

 

Published Tuesday, July 25, 2006 6:14 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker