c# console application - prevent default exception dialog

c#, console-application, dialog, exception

Solution

There's an unhandled exception event you can subscribe to in the application domain.

    public static void Main()   
    {   
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);

        //some code here....
    }   

    /// <summary>
    /// Occurs when you have an unhandled exception
    /// </summary>
    public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)   
    { 
        //here's how you get the exception  
        Exception exception = (Exception)e.ExceptionObject;  

        //bail out in a tidy way and perform your logging
    }

Problem

I have simple application with single AppDomain which is periodicaly launched on a server. Sometimes unhandled exception occurs in the aplication and default abort/retry/ignore dialog pops up. I need to somehow prevent the edialog from showing and just output the exception on StrErr and close the application. So I enclosed all the code in main method with try-catch statement, but it didn't help at all - the exception dialog is still shown sometimes. The Main() code looks like this: ``` try { RunApplication(); } catch (Exception exc) { Console.Error.WriteLine(exc.ToString()); Console.Error.WriteLine(exc.StackTrace); if (exc.InnerException != null) { Console.Error.WriteLine(exc.InnerException.ToString()); Console.Error.WriteLine(exc.InnerException.StackTrace); } Environment.Exit(666); } ``` This try-catch clause shoud catch all unhandled exceptions and the exception dialog should never popup AFAIK. Am I missing something? Or is there any setting (registry etc) on the server which controls some special behaviour related to the exception dialog/application error code?

Original source