Grant Bagwell
Grant Bagwell

Reputation: 53

Supress unhandled errors c# when built

I use the following piece of code to capture any unhandled errors in my VS2012 C# program:

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

In the Event Handlers I display a message to the user and in certain occasions e-mail myself the StackTrace followed always by a Application.Exit();

In the example

throw new System.Exception("Parameter cannot be null");

The error handlers are successfully called however when debugging it still highlights the error as unhandled after my error handlers are called. I can understand this may be the correct behaviour for the development environment. However when building the project it does a similar thing in that my message box / email is successfully called but then I get the program crash dialog from Windows 7 (with the option to Close / Restart / Debug).

I understand the Application.Exit() simply sends a message to all threads to close. How do I indicate to the program that it should ignore this error (as it has already been handled)?

Thanks in advance!

Upvotes: 0

Views: 133

Answers (2)

Jan Dörrenhaus
Jan Dörrenhaus

Reputation: 6717

Actually, Application.Exit will just tell the WinForms main thread message pump to close. If that message pump is already broken, due to error, this will not do anything. Plus, any custom threads will not care about it at all.

Instead, use Environment.Exit.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941455

followed always by a Application.Exit()

That merely starts the shutdown of an app. It can also be canceled with a FormClosing event handler. Clearly you want to shutdown the app immediately, use Environment.Exit() instead.

Also note that you do not want the Application class to catch the exception. So use UnhandledExceptionMode.ThrowException instead. You now no longer have to bother with writing an event handler for Application.ThreadException either, all aborts now go through the AppDomain.UnhandledException event.

Do beware that this event makes debugging difficult, you still want the Exception Assistant to help you diagnose accidents while you debug. So make it conditional, like this:

    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
        if (!System.Diagnostics.Debugger.IsAttached) {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
        Application.Run(new Form1());
    }

And temporarily disable that test if you want to debug your crash handler.

Upvotes: 1

Related Questions