Unhandled Exception in Winforms Application

8.1k views Asked by At

I have a simple WinForms app that is used to enter test cases. Ever since I upgraded this application to .NET 4.0 and added a new tab page to the tab page control for validating XML against XSD schema the application has been randomly crashing. I've been unable to reproduce the exception.

The error my QA guy receives is the generic Windows message:

TestCaseViewer has encountered a problem and needs to close. We are sorry for the inconvenience.

To try to get to the real error I've added the following code to the beginning of the Main method of program:

        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
        Application.ThreadException += Application_ThreadException;

The event handlers look like this:

    static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        try
        {
            MessageBox.Show(e.Exception.ToString(), @"Thread Exception", 
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        finally 
        {
            Application.Exit();    
        }
    }

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        try
        {
            var ex = (Exception)e.ExceptionObject;
            MessageBox.Show(ex.ToString(), @"Unhandled Exception",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        finally 
        {
            Application.Exit();    
        }
    }

Unfortunately this hasn't helped and whatever is thowing the error continues to do so in a way that generates the unhandled error that is bubbling up to the OS.

Can anyone give me any other ideas about trapping this exception?

2

There are 2 answers

8
Cody Gray - on strike On

If you're using Visual Studio, you can set it to break on all unhandled exceptions and even any time that an exception is thrown, regardless of whether or not it is handled by your code.

To do this, select "Exceptions" from the "Debug" menu. You'll get a dialog box that looks like this:

  Visual Studio Exceptions dialog

If you really want to get serious, try checking all of the boxes. Then, find out from your QA guy what exactly is being done to trigger the exception, and reproduce those actions exactly while running under the debugger within the development environment. Whenever the exception is thrown, Visual Studio will break and you'll see the offending line of code along with a complete stack trace.

1
Robert Slade Lewis On

Try adding the following to your app.config

<runtime>
   <!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
   <legacyUnhandledExceptionPolicy enabled="1" />
</runtime>