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.