Saturday, 20 July 2013

Microsoft DotNet Framework - Catch the UnHandled Exception in Application

              This article discuss about the information related to Catch the UnHandled Exception for application. Whenever a application crashes due to unhandled exception, We dont have information why it crashes, What type of exception is unhandled, Where it is raises

UnHandled Exception :
            Unhandled Exception event handles the exceptions that are unhandled or not catched from Main UI Thread

Thread Exception :
           Thread Exception event handles the exceptions that are unhandled or not catched from Threads that are Non UI.

For Windows Application , We can ignore or log the error and keep on running the application by using Thread Exception.

static void Main()
  Application.ThreadException += new ThreadExceptionEventHandler(App_ThreadException;
  AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Cur_UnhandledException);
  Application.Run(new Form1());

static void App_ThreadException(object sender, ThreadExceptionEventArgs e)
  MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
  File.AppendAllText(@"D:\thread.log",e.Exception.StackTrace)                          //If you need to terminate the Application uncomment the following line              // Application.Exit()                                                              }                                                                                     
static void Cur_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception";
  File.AppendAllText(@"D:\unhandex.log",(e.ExceptionObject as Exception).StackTrace); )

For web Application Some times Application restarts and Session Expries because of UnHandled Error How to overcome this.

Change the config file from the following path

C:\>type %WINDIR%\Microsoft.NET\Framework\v2.0.50727\aspnet.config

<configuration>                                                                                 <runtime>                                                                                           <legacyUnhandledExceptionPolicy enabled="true" />