Is there a setting that is preventing the unhandled exception dialog from displaying in apps that I compile?

前端 未结 2 1471
广开言路
广开言路 2020-12-05 21:35

I\'m not sure if this is the right place to ask but I shall anyway.

I have 2 .NET applications; one that was compiled by myself, the other not. Both use .NET Framewo

相关标签:
2条回答
  • 2020-12-05 22:24

    The solution presented by Hans Passant will terminate the application. This also means that remaining finally blocks are not executed any more.

    You can also use PInvoke to change the behavior by calling the SetErrorMode() method.

    public enum ErrorModes : uint
    {
        SYSTEM_DEFAULT = 0x0,
        SEM_FAILCRITICALERRORS = 0x0001,
        SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
        SEM_NOGPFAULTERRORBOX = 0x0002,
        SEM_NOOPENFILEERRORBOX = 0x8000,
        SEM_NONE = SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX
    }
    
    [DllImport("kernel32.dll")]
    static extern ErrorModes SetErrorMode(ErrorModes uMode);
    

    and then call

    SetErrorMode(ErrorModes.SEM_NONE);
    

    Doing so will give the finally blocks the chance to run.

    0 讨论(0)
  • 2020-12-05 22:38

    The top screen-shot is a ThreadExceptionDialog. It is displayed in the very specific case where a Winforms app bombs in an event handler that was fired by the message loop (Application.Run) and the app didn't otherwise reassign the Application.ThreadException event handler. Using it is not a very good practice, there's no reasonable way the user could know whether to click the Continue or Quit button. Be sure to call Application.SetUnhandledExceptionMode() to disable it.

    The bottom screen-shot is the default Windows error reporting dialog, displayed by Windows when a program bombed on an unhandled exception. You should never let it get to this point, the dialog doesn't display enough information to help anybody diagnose and fix the problem. Always write an event handler for the AppDomain.CurrentDomain.UnhandledException event. Display and/or log e.ExceptionObject.ToString() and call Environment.Exit() to terminate the app.

    Make your Program.cs source code look similar to this:

        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.Run(new Form1());
        }
    
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
            // TODO: improve logging and reporting
            MessageBox.Show(e.ExceptionObject.ToString());
            Environment.Exit(-1);
        }
    
    0 讨论(0)
提交回复
热议问题