Is there any reason to prefer one of these methods of implementing a global exception handler in a Windows Forms application over the other?
First Method
static void Main(string[] args)
{
try
{
System.Windows.Forms.Application.Run(mainform);
}
catch (Exception ex)
{
// Log error and display error message
}
}
Second Method
static void Main(string[] args)
{
System.Windows.Forms.Application.ThreadException +=
new ThreadExceptionEventHandler(Application_ThreadException);
System.Windows.Forms.Application.Run(mainform);
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
// Log error and display error message
}
Does handling the ThreadException event give you something that the try / catch doesn't?
My understanding of this behavior is that adding a ThreadException handler will cause otherwise unhandled exceptions in forms to be caught and processed by this handler, which will allow the application to continue running.
In your try/catch design, the first unhandled exception in a form will cause the application to halt. You will catch the exception, but the application will then come to an end.
Note that there is also an AppDomain.UnhandledException event that will be raised in certain cases (unhandled exceptions in threads other than the main windows forms thread and not catching the ThreadException), all of which are very bad news for your app.
The event handler approach allows your app to catch the exception, try to recover from it and continue. (i.e. execution does not leave Application.Run
)
A try/catch
in main will catch the exception but you will have left Application.Run
at which point about all you can do is exit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With