softpcapps Software CODE HELP BLOG

Shareware and free Open Source Windows Software Applications and free Online Tools

How to catch unhandled Exceptions

One thing that is absolutely necessary in any .NET application is to handle uncatched Exceptions.
Just think that if you do not catch an exception just one time the whole application will nearly crash and an ugly message will be displayed.
To catch unhandled exeptions the easy way, add exception handlers for AppDomain.CurrentDomain and Application.ThreadException.
On the top of Program.cs always include this :


Now add the following class to your project :
	class ExceptionHandlersHelper
        public static void AddUnhandledExceptionHandlers()
            // Define a handler for unhandled exceptions.
            AppDomain.CurrentDomain.UnhandledException +=
                new System.UnhandledExceptionEventHandler(myExceptionHandler);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(

        private static void myExceptionHandler(object sender, UnhandledExceptionEventArgs e)
            Exception ex = (Exception)e.ExceptionObject;            



        private static void myThreadExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
            Exception ex = (Exception)e.Exception;