none
【C# .net】 windowForm程序中怎么设置全局异常处理? RRS feed

答案

  • 你好!
         一般使用Application的ThreadException事件,可以参考这个例子:
    // Creates a class to throw the error.
     public class ErrorHandler : System.Windows.Forms.Form {
     
        // Inserts the code to create a form with a button.
     
        // Programs the button to throw an exception when clicked.
        private void button1_Click(object sender, System.EventArgs e) {
           throw new ArgumentException("The parameter was invalid");
        }
     
        public static void Main(string[] args) {
           // Creates an instance of the methods that will handle the exception.
           CustomExceptionHandler eh = new CustomExceptionHandler();
     
           // Adds the event handler to to the event.
           Application.ThreadException += new ThreadExceptionEventHandler(eh.OnThreadException);
     
           // Runs the application.
           Application.Run(new ErrorHandler());
        }
     }
     
     // Creates a class to handle the exception event.
     internal class CustomExceptionHandler {
     
        // Handles 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();
              }
           }
    
           // Exits the program when the user clicks Abort.
           if (result == DialogResult.Abort) 
              Application.Exit();
        }
     
        // Creates the error message and displays it.
        private DialogResult ShowThreadExceptionDialog(Exception e) {
           string errorMsg = "An error occurred please contact the adminstrator with the following information:\n\n";
           errorMsg = errorMsg + e.Message + "\n\nStack Trace:\n" + e.StackTrace;
           return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
        }
     }
    

    周雪峰
    2009年10月14日 14:20
    版主