AppDomain.CurrentDomain.UnhandledException未在没有调试的情况下触发

And*_*eek 14 .net exception unhandled-exception

我有一个.NET程序,其事件处理程序绑定到Application.CurrentDomain.UnhandledException.使用调试运行程序时,抛出未处理的异常时会触发此事件.但是,在没有调试的情况下运行时,事件不会触发.

我的问题是什么?

谢谢,安德鲁

Dan*_*ner 16

我假设你没有设置正确的异常处理模式Application.SetUnhandledExceptionMode()- 只需将其设置为UnhandledExceptionMode.ThrowException.

UPDATE

我刚刚写了一个小测试应用程序,发现没有任何工作未被发现.您可以尝试使用此测试代码重现您的错误吗?

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApplication
{
    public static class Program
    {
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;

            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            Application.Run(new TestForm());

            throw new Exception("Main");
        }

        static void Application_ThreadException(Object sender, ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message, "Application.ThreadException");
        }

        static void AppDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show(((Exception)e.ExceptionObject).Message, "AppDomain.UnhandledException");
        }
    }

    public class TestForm : Form
    {
        public TestForm()
        {
            this.Text = "Test Application";
            this.ClientSize = new Size(200, 60);
            this.MinimumSize = this.Size;
            this.MaximumSize = this.Size;
            this.StartPosition = FormStartPosition.CenterScreen;

            Button btnThrowException = new Button();

            btnThrowException.Text = "Throw";
            btnThrowException.Location = new Point(0, 0);
            btnThrowException.Size = new Size(200, 30);
            btnThrowException.Click += (s, e) => { throw new Exception("Throw"); };

            Button btnThrowExceptionOnOtherThread = new Button();

            btnThrowExceptionOnOtherThread.Text = "Throw on other thread";
            btnThrowExceptionOnOtherThread.Location = new Point(0, 30);
            btnThrowExceptionOnOtherThread.Size = new Size(200, 30);
            btnThrowExceptionOnOtherThread.Click += (s, e) => new Thread(() => { throw new Exception("Other thread"); }).Start();

            this.Controls.Add(btnThrowException);
            this.Controls.Add(btnThrowExceptionOnOtherThread);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)