static class Program
{
[STAThread]
static void Main()
{
/* From my understanding this should install the exception handler */
Application.ThreadException += GetEventHandler();
/* Since posting this question I have found that I need to add the
following line, but even with the following line in place the
exceptions thrown are not caught.... */
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
/* Some auto generated code here */
Application.Run(new MyForm());
}
private static ThreadExceptionEventHandler GetEventHandler()
{
return new ThreadExceptionEventHandler(OnThreadException);
}
private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show("Big error...");
}
}
根据:
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception%28v=vs.71%29.aspx
这应该工作。但是当在MyForm
类内部抛出异常时,它不会显示“Big error ...”消息框,但告诉我没有异常处理程序。任何建议将不胜感激。
答案 0 :(得分:2)
您需要将UnhandleExceptionMode
设置为CatchException
/* From my understanding this should install the exception handler */
Application.ThreadException += GetEventHandler();
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
/* Some auto generated code here */
Application.Run(new MyForm());
Application.ThreadException
只能捕获UI线程中引发的异常。在由于Windows通知而运行的代码中。或者在技术术语中,由消息循环触发的事件。大多数Winforms事件都符合这一类别。
它做什么 not 陷阱是在任何非UI线程上引发的异常,例如以Thread.Start()
,ThreadPool.QueueUserWorkItem
或委托{s}开头的工作线程{1}}方法。这些中的任何未处理的异常都将终止该应用程序。