我有一个使用.NET编写的程序,其中一个事件处理程序绑定了Application.CurrentDomain.UnhandledException事件。当以调试模式运行程序时,该事件在未处理异常时触发。但是,在不进行调试的情况下,该事件不会触发。
我的问题是什么?
谢谢, Andrew
我有一个使用.NET编写的程序,其中一个事件处理程序绑定了Application.CurrentDomain.UnhandledException事件。当以调试模式运行程序时,该事件在未处理异常时触发。但是,在不进行调试的情况下,该事件不会触发。
我的问题是什么?
谢谢, Andrew
我假设你没有使用Application.SetUnhandledExceptionMode()
设置正确的异常处理模式 - 只需将其设置为UnhandledExceptionMode.ThrowException
。
更新
我刚写了一个小测试应用程序,发现没有遇到任何意外情况。你能否尝试使用这个测试代码来重现你的错误?
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);
}
}
}
AppDomain.UnhandledException
事件的作用就是让你在其他线程有未处理的异常时得到通知。如果一个线程有未处理的异常,进程将会像你所描述的那样终止。请注意,该事件只能提供通知,无法阻止进程终止。 - Martin Liversage