Application.OnThreadException 方法

引发 ThreadException 事件。

**命名空间:**System.Windows.Forms
**程序集:**System.Windows.Forms(在 system.windows.forms.dll 中)

语法

声明
Public Shared Sub OnThreadException ( _
    t As Exception _
)
用法
Dim t As Exception

Application.OnThreadException(t)
public static void OnThreadException (
    Exception t
)
public:
static void OnThreadException (
    Exception^ t
)
public static void OnThreadException (
    Exception t
)
public static function OnThreadException (
    t : Exception
)

参数

  • t
    一个 Exception,它代表所引发的异常。

备注

该事件使应用程序能够智能地处理异常。窗口过程在收到线程异常时调用该事件。将您的事件处理程序附加到该事件。

引发事件时会通过委托调用事件处理程序。有关更多信息,请参见 引发事件

OnThreadException 方法还允许派生类对事件进行处理而不必附加委托。这是在派生类中处理事件的首选技术。

提示

Application 类有 ThreadException 事件。可以将事件处理程序附加到该事件中,以执行任何必要的自定义处理。

给继承者的说明 在派生类中重写 OnThreadException 时,一定要调用基类的 OnThreadException,以便注册的委托接收事件。

示例

下面的代码示例在窗体上的 button1 被单击时引发 ThreadException 事件。示例创建两个类。ErrorHandler 类创建引发该事件的窗体和按钮。CustomExceptionHandler 类提供处理异常的方法。

ErrorHandler 类的 Main 中,这段代码创建异常处理类的新实例(即 CustomExceptionHandler 的实例)。然后该实例被添加到事件中,并且运行应用程序。

CustomExceptionHandler 类的 OnThreadException 方法中,此示例使用 try...catch...finally 语句处理异常。ShowThreadExceptionDialog 方法创建要显示的消息并在消息框中显示。

Imports System
Imports System.IO
Imports System.Windows.Forms
Imports System.Threading
Imports System.Drawing

Public Class Form1
    Inherits Form

    ' Inserts code to create a form with a button.
    Private WithEvents Button1 As Button

    Sub New()
        Me.Size = New Size(600, 100)

        Button1 = New Button()
        Button1.Text = "Click Me"
        Button1.Location = New Point(10, 10)
        Me.Controls.Add(Button1)
    End Sub

    ' Programs the button to throw the exception when clicked.
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Throw New ArgumentException("The parameter was invalid")
    End Sub

    <STAThread()> _
    Shared Sub Main()
        ' Creates an instance of the methods that will handle the exception.
        Dim eh As CustomExceptionHandler = New CustomExceptionHandler()

        ' Adds the event handler  to the event.
        AddHandler Application.ThreadException, AddressOf eh.OnThreadException

        ' Runs the application.
        Application.Run(New Form1())
    End Sub
End Class

' Create a class to handle the exception event.
Friend Class CustomExceptionHandler

    ' Handles the exception event.
    Public Sub OnThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
        Dim result As DialogResult = System.Windows.Forms.DialogResult.Cancel
        Try
            result = Me.ShowThreadExceptionDialog(t.Exception)
        Catch
            Try
                MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
            Finally
                Application.Exit()
            End Try
        End Try

        ' Exits the program when the user clicks Abort.
        If (result = System.Windows.Forms.DialogResult.Abort) Then
            Application.Exit()
        End If
    End Sub

    ' Creates the error message and displays it.
    Private Function ShowThreadExceptionDialog(ByVal e As Exception) As DialogResult
        Dim errorMsg As StringWriter = New StringWriter()
        errorMsg.WriteLine("An error occurred please contact the adminstrator with the following information:")
        errorMsg.WriteLine("")
        errorMsg.WriteLine(e.Message)
        errorMsg.WriteLine("")
        errorMsg.WriteLine("Stack Trace:")
        errorMsg.WriteLine(e.StackTrace)
        Return MessageBox.Show(errorMsg.ToString(), "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
    End Function
End Class
using System;
using System.Windows.Forms;
using System.Threading;
using System.Drawing;

public class Form1 : Form
{
    // Inserts code to create a form with a button.
    Button button1;

    private Form1()
    {
        this.Size = new Size(600, 100);

        button1 = new Button();
        button1.Click += new EventHandler(button1_Click);
        button1.Text = "Click Me"; 
        button1.Location = new Point (10, 10);
        this.Controls.Add(button1);
    }
 
    // Programs the button to throw the 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 the event.
       Application.ThreadException += new ThreadExceptionEventHandler(eh.OnThreadException);
 
       // Runs the application.
       Application.Run(new Form1());
    }
 }
 
 // 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);
    }
 }
public:
   // Creates a class to throw the error.
   ref class ErrorHandler: public System::Windows::Forms::Form
   {
      // Inserts code to create a form with a button.

      // Programs the button to throw the exception when clicked.
   private:
      void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
      {
         throw gcnew ArgumentException( "The parameter was invalid" );
      }

   public:
      static void Main()
      {
         // Creates an instance of the methods that will handle the exception.
         CustomExceptionHandler ^ eh = gcnew CustomExceptionHandler;
         
         // Adds the event handler  to the event.
         Application::ThreadException += gcnew ThreadExceptionEventHandler( eh, &Form1::CustomExceptionHandler::OnThreadException );
         
         // Runs the application.
         Application::Run( gcnew ErrorHandler );
      }
   };

   // Creates a class to handle the exception event.
internal:
   ref class CustomExceptionHandler
   {
   public:
      // Handles the exception event.
      void OnThreadException( Object^ /*sender*/, ThreadExceptionEventArgs^ t )
      {
         System::Windows::Forms::DialogResult result = System::Windows::Forms::DialogResult::Cancel;
         try
         {
            result = this->ShowThreadExceptionDialog( t->Exception );
         }
         catch ( Exception^ ) 
         {
            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:
      System::Windows::Forms::DialogResult ShowThreadExceptionDialog( Exception^ e )
      {
         String^ errorMsg = "An error occurred please contact the adminstrator with the following information:\n\n";
         errorMsg = String::Concat( errorMsg, e->Message, "\n\nStack Trace:\n", e->StackTrace );
         return MessageBox::Show( errorMsg, "Application Error", MessageBoxButtons::AbortRetryIgnore, MessageBoxIcon::Stop );
      }
   };
// Creates a class to throw the error.
public static class ErrorHandler extends System.Windows.Forms.Form
{
    // Inserts code to create a form with a button.
    // Programs the button to throw the exception when clicked.
    private void button1_Click(Object sender, System.EventArgs e)
    {
        throw new ArgumentException("The parameter was invalid");
    } //button1_Click

    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 the event.
        Application.add_ThreadException(
            new ThreadExceptionEventHandler(eh.OnThreadException));

        // Runs the application.
        Application.Run(new ErrorHandler());
    } //main
} //ErrorHandler

// Creates a class to handle the exception event.
private static class CustomExceptionHandler
{
    // Handles the exception event.
    private void OnThreadException(Object sender, ThreadExceptionEventArgs t)
    {
        DialogResult result = DialogResult.Cancel;

        try {
            result = this.ShowThreadExceptionDialog(t.get_Exception());
        }
        catch (System.Exception exp) {
            try {
                MessageBox.Show("Fatal Error", "Fatal Error", 
                    MessageBoxButtons.AbortRetryIgnore, 
                    MessageBoxIcon.Stop);
            }
            finally {
                Application.Exit();
            }
        }

        // Exits the program when the user clicks Abort.
        if (result.Equals(DialogResult.Abort)) {
            Application.Exit();
        }
    } //OnThreadException

    // Creates the error message and displays it.
    private DialogResult ShowThreadExceptionDialog(System.Exception e)
    {
        String errorMsg = "An error occurred please contact the"
            + " administrator with the following information:\n\n";
        errorMsg = errorMsg + e.get_Message() + "\n\nStack Trace:\n"
            + e.get_StackTrace();
        return MessageBox.Show(errorMsg, "Application Error", 
            MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
    } //ShowThreadExceptionDialog
} //CustomExceptionHandler

public static void main(String[] args)
{
    ErrorHandler.main(args);
}//main

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

请参见

参考

Application 类
Application 成员
System.Windows.Forms 命名空间