Thursday, September 16, 2004

Handling Unhandled Exceptions in .NET

Depending on the type of application you are creating, .NET has three different global exception handlers.
For ASP.NET look at:System.Web.HttpApplication.Error eventNormally placed in your Global.asax file.
For console applications look at:System.AppDomain.UnhandledException eventUse AddHandler in your Sub Main.
For Windows Forms look at:System.Windows.Forms.Application.ThreadException eventUse AddHandler in your Sub Main.
This is called Vectored Exception handling.

It can be beneficial to combine the above global handlers in your app, as well as wrap your Sub Main in a try catch itself.
There is an article in the June 2004 MSDN Magazine that shows how toimplement the global exception handling in .NET that explains why & when youuse multiple of the above handlers...
http://msdn.microsoft.com/msdnmag/issues/04/06/NET/default.aspx

Example: In a Win Forms App, have a handler attached to the Application.ThreadException event, plus a Try/Catch in my Main. The Try/Catch in Main only catches exceptions if the constructor of the MainFormraises an exception, the Application.ThreadException handler will catch all uncaught exceptions from any form/control event handlers.

No comments: