【发布时间】:2015-01-16 21:06:41
【问题描述】:
首先让我说我已经彻底阅读了this useful article,并且正在使用 CodeProject 中的 SafeThread 类。无论使用 Thread 还是 SafeThread,我都会得到相同的结果。
我已将我的问题简化为一个包含两个表单的应用程序,每个表单都有一个按钮。主程序显示一个表格。当您单击该按钮时,会启动一个新线程,该线程会显示第二个表单。当您单击第二个表单上的按钮时,在内部它只是“抛出新的异常()”
当我在 VS2008 下运行它时,我看到“DoRun() 中的异常”。
当我在 VS2008 之外运行时,我得到一个对话框“您的应用程序中发生了未处理的异常。如果您单击继续,应用程序...。”
我已尝试将 app.config 中的 legacyUnhandledExceptionPolicy 设置为 1 和 0。
当不在 VS2008 下运行时,我需要做什么来捕获在我的第二种形式中引发的异常?
这是我的 Program.cs
static class Program
{
[STAThread]
static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler (Application_ThreadException);
Application.SetUnhandledExceptionMode (UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
catch(Exception ex)
{
MessageBox.Show("Main exception");
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show("CurrentDomain_UnhandledException");
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show("Application_ThreadException");
}
}
这是 Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SafeThread t = new SafeThread(new SimpleDelegate(ThreadMain));
try
{
t.ShouldReportThreadAbort = true;
t.ThreadException += new ThreadThrewExceptionHandler(t_ThreadException);
t.ThreadCompleted += new ThreadCompletedHandler(t_ThreadCompleted);
t.Start();
}
catch(Exception ex)
{
MessageBox.Show(string.Format("Caught externally! {0}", ex.Message));
}
}
void t_ThreadCompleted(SafeThread thrd, bool hadException, Exception ex)
{
MessageBox.Show("t_ThreadCompleted");
}
void t_ThreadException(SafeThread thrd, Exception ex)
{
MessageBox.Show(string.Format("Caught in safe thread! {0}", ex.Message));
}
void ThreadMain()
{
try
{
DoRun();
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Caught! {0}", ex.Message));
}
}
private void DoRun()
{
try
{
Form2 f = new Form2();
f.Show();
while (!f.IsClosed)
{
Thread.Sleep(1);
Application.DoEvents();
}
}
catch(Exception ex)
{
MessageBox.Show("Exception in DoRun()");
}
}
}
这是Form2:
public partial class Form2 : Form
{
public bool IsClosed { get; private set; }
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
throw new Exception("INTERNAL EXCEPTION");
}
protected override void OnClosed(EventArgs e)
{
IsClosed = true;
}
}
【问题讨论】:
-
你到底想要什么样的行为?
-
异常中的堆栈跟踪是什么?
-
我希望我的异常处理程序之一捕获在 form2 中 button1_Click 中抛出的异常;这发生在 VS2008 中,但不在外部 这是堆栈跟踪的顶部 Trapper.Form2.button1_Click(Object sender, EventArgs e) in C:\codefarm\Trapper\Form2.cs:system.Windows.Forms.Control 的第 17 行。 System.Windows.Forms.Button.OnClick(EventArgs e) 处的 OnClick(EventArgs e)
标签: c# .net exception-handling