Thursday, November 28, 2013

Multithreading : winforms Error handling

This is code handling exceptions from threads.

[STAThread]
private static void Main()
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
catch (Exception e)
{
HandleApplicationTerminating(e);
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is Exception)
{
var exception = (Exception) e.ExceptionObject;
if (e.IsTerminating)
HandleApplicationTerminating(exception);
else
HandleException(exception);
}
}
private static void HandleApplicationTerminating(Exception e)
{
if (Debugger.IsAttached)
Debugger.Break();
MessageBox.Show("Application terminating\nException thrown : " + e.Message);
}
private static void HandleException(Exception exception)
{
if (Debugger.IsAttached)
Debugger.Break();
MessageBox.Show("Exception thrown : " + exception.Message);
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
HandleException(e.Exception);
}
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment