I have written a WinForms application which performs some sort of syncing work. I want it to keep running despite of any occurrence of exceptions so that syncing keeps on going with next attempts. Thus, I have written the app such a way that whenever an exception occurs, it logs the exception stack trace, performs some diagnostics, then logs the diagnostics information and continues with next syncing attempts.
For uncaught exceptions I added Exception handlers for Application.ThreadException
and also for AppDomain.CurrentDomain.UnhandledException
in my Main()
thread:
static void Main(string[] args)
{
Application.ThreadException += new ThreadExceptionEventHandler(UIThreadExceptionHandler);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new myForm());
}
//exception handlers
public static void UIThreadExceptionHandler(object sender, ThreadExceptionEventArgs t)
{
logger.Fatal("Fatal Windows Forms Error");
logStackTrace(t.Exception); //logs the stack trace with some desired formatting
Application.Exit(new CancelEventArgs(true));
}
public static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs t)
{
logger.Fatal("Fatal Application Error");
logStackTrace((Exception)(t.ExceptionObject)); //logs the stack trace with some desired formatting
Application.Exit(new CancelEventArgs(true));
}
I kept my app running for testing and realized that whenever Application.ThreadException
is caught, the app correctly logs the string Fatal Windows Forms Error
, followed by the exception stack trace and then the application exits.
I dont want the app to exit. I just want that it should log the exception stack trace and continue with next syncing attempt. The exception that is occurring in UI thread is not that severe one, since the same exception also occurred in the other/non-UI threads of the app, but it did not crashed the app (as I can see this in logs). However when the same exception occurs in the UI thread, the app crashes.
See Question&Answers more detail:os