为未捕获的异常添加错误处理程序 在应用程序设计中,可能希望为在应用程序中没有处理的任何异常注册一个异常处理程序。可以通过调用 Application.AddOnThreadException 方法并在应用程序中传入对某方法的引用来为未处理的异常创建异常处理程序。然后为该线程上任何未处理的异常调用此方法。当 Windows 窗体窗口过程接收异常时,引发 OnThreadException 事件。 Windows 窗体提供一个默认的异常处理程序和名为 ThreadExceptionDialog 的异常处理对话框。可以在开发过程中使用此对话框,但您可能希望在应用程序开发接近完成时,为应用程序提供您自己的自定义异常处理程序。 下面的示例演示如何创建非常简单的自定义异常处理程序,该处理程序在 MessageBox 中显示异常消息和堆栈跟踪: //The Error Handler class //We need a class because event handling methods can't be static internal class CustomExceptionHandler { //Handle the exception event public void OnThreadException(object sender, ThreadExceptionEventArgs t) { DialogResult result = DialogResult.Cancel; try { result = this.ShowThreadExceptionDialog(t.Exception); } catch { try { MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop); } finally { Application.Exit(); } } if (result == DialogResult.Abort) Application.Exit(); } //The simple dialog that is displayed when this class catches and exception private DialogResult ShowThreadExceptionDialog(Exception e) { string errorMsg = "An error occurred please contact the adminstrator with" + " the following information:\n\n"; errorMsg += e.Message + "\n\nStack Trace:\n" + e.StackTrace; return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop); } } .... //Register the custom error handler as soon as we can in Main //to make sure that we catch as many exceptions as possible public static void Main(string[] args) { CustomExceptionHandler eh = new CustomExceptionHandler(); Application.ThreadException += new ThreadExceptionEventHandler(eh.OnThreadException); Application.Run(new ErrorHandler()); 字体:大 中 小 |