Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between handling Application.ThreadException and wrapping Application.Run in Try / Catch

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?

like image 380
kevev22 Avatar asked Dec 09 '11 22:12

kevev22


2 Answers

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.

like image 186
competent_tech Avatar answered Oct 05 '22 23:10

competent_tech


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.

like image 42
dkackman Avatar answered Oct 06 '22 01:10

dkackman