Share via


How to handle Unhandled Exceptions

When an exception occurs is thrown in your application, but is never caught the application ends up crashing.  Not exactly a user friendly application.  So that you can better handle these unhandled exceptions and at the minimum close the application gracefully you can provide an Unhandled Exception Handler.

 

Here is some code that shows how to do this.

 

[STAThread]

static void Main() {

 

// Add and event handler to handle unhandled exceptions.

Application.ThreadException += new ThreadExceptionEventHandler(OnUnhandledException);

 

Application.Run(new FormStartUp());

}

 

 

// Unhandled exception handler

static void OnUnhandledException(object sender, ThreadExceptionEventArgs t) {

 

// Do something to handle the exception, notify the user, and/or clean up resources.

 

}

 

This is the way that I do it in almost every application I have written.  Another option may be to use UnhandledException Handler of the AppDomain.  I'm not quite sure of the differences, however, here is a blog post that talks about AppDomain Unhandled Exception.

Comments

  • Anonymous
    February 17, 2005
    My question is if I use this in my asp.net application, I should NOT use the static type in the unhandled exception handler. Correct? Great Tip btw!!!
  • Anonymous
    February 17, 2005
    Hello,

    Yes that would be correct that you would not want to make this type of functionality static in a web application. However, in a web app, unhandled exceptions are handled differently. Main does not exist in a web application, however, in the Web.config you can specify a page to display when an exception is not handled.

    Take care,

    Tom
  • Anonymous
    February 17, 2005
    Kind of funny,

    In my last response, I couldn't remember the config tag for specifying the error page so I didn't put it knowing if you look at the web config you would find it. Then when I clicked submit to post my response, the site gave me an error screen displaying the webconfig. So I copied the tag and here it is.

    <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>

    Tom
  • Anonymous
    February 17, 2005
    I have the full story on unhandled exceptions for both .NET 1.0 and .NET 2.0 (for both CF and full fx) on my blog. A good starting point is this one:
    http://www.danielmoth.com/Blog/2004/12/appdomainunhandledexception-part-1.html
  • Anonymous
    April 07, 2008
    Global Exception Handling in C#