Application.ThreadException 이벤트

정의

포착되지 않은 스레드 예외가 throw될 때 발생합니다.Occurs when an untrapped thread exception is thrown.

public:
 static event System::Threading::ThreadExceptionEventHandler ^ ThreadException;
public static event System.Threading.ThreadExceptionEventHandler ThreadException;
member this.ThreadException : System.Threading.ThreadExceptionEventHandler 
Public Shared Custom Event ThreadException As ThreadExceptionEventHandler 

이벤트 유형

ThreadExceptionEventHandler

예제

다음 코드 예제에서는 Windows Forms 스레드에서 발생 하는 예외 및 다른 스레드에서 발생 하는 예외에 대 한 이벤트 처리기를 설정 합니다.The following code example sets event handlers for exceptions that occur on Windows Forms threads and exceptions that occur on other threads. SetUnhandledExceptionMode응용 프로그램의 사용자 구성 파일에 있는 설정에 관계 없이 응용 프로그램에서 모든 예외를 처리 하도록를 설정 합니다.It sets SetUnhandledExceptionMode so that all exceptions are handled by the application, regardless of the settings in the application's user configuration file. 이벤트를 사용 하 여 ThreadException ui 스레드 예외를 처리 하 고 이벤트를 사용 하 여 UnhandledException ui가 아닌 스레드 예외를 처리 합니다.It uses the ThreadException event to handle UI thread exceptions, and the UnhandledException event to handle non-UI thread exceptions. UnhandledException에서는 응용 프로그램이 종료 되는 것을 방지할 수 없기 때문에이 예제에서는 종료 전에 응용 프로그램 이벤트 로그에 오류를 기록 합니다.Since UnhandledException cannot prevent an application from terminating, the example simply logs the error in the application event log before termination.

이 예제에서는 클래스에 및 라는 두 개의 컨트롤을 정의 했다고 가정 Button button1 button2 Form 합니다.This example assumes that you have defined two Button controls, button1 and button2, on your Form class.

   // Creates a class to throw the error.
public:
   ref class ErrorHandler: public 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 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
   {
      // Handles the exception event.
   public:
      void OnThreadException( Object^ /*sender*/, ThreadExceptionEventArgs^ t )
      {
         System::Windows::Forms::DialogResult result = ::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 );
      }
   };
Thread newThread = null;

// Starts the application.
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{
    // Add the event handler for handling UI thread exceptions to the event.
    Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);

    // Set the unhandled exception mode to force all Windows Forms errors to go through
    // our handler.
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

    // Add the event handler for handling non-UI thread exceptions to the event.
    AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

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

// 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");
}

// Start a new thread, separate from Windows Forms, that will throw an exception.
private void button2_Click(object sender, System.EventArgs e)
{
    ThreadStart newThreadStart = new ThreadStart(newThread_Execute);
    newThread = new Thread(newThreadStart);
    newThread.Start();
}

// The thread we start up to demonstrate non-UI exception handling.
void newThread_Execute()
{
    throw new Exception("The method or operation is not implemented.");
}

// Handle the UI exceptions by showing a dialog box, and asking the user whether
// or not they wish to abort execution.
private static void Form1_UIThreadException(object sender, ThreadExceptionEventArgs t)
{
    DialogResult result = DialogResult.Cancel;
    try
    {
        result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception);
    }
    catch
    {
        try
        {
            MessageBox.Show("Fatal Windows Forms Error",
                "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
        }
        finally
        {
            Application.Exit();
        }
    }

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

// Handle the UI exceptions by showing a dialog box, and asking the user whether
// or not they wish to abort execution.
// NOTE: This exception cannot be kept from terminating the application - it can only
// log the event, and inform the user about it.
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    try
    {
        Exception ex = (Exception)e.ExceptionObject;
        string errorMsg = "An application error occurred. Please contact the adminstrator " +
            "with the following information:\n\n";

        // Since we can't prevent the app from terminating, log this to the event log.
        if (!EventLog.SourceExists("ThreadException"))
        {
            EventLog.CreateEventSource("ThreadException", "Application");
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "ThreadException";
        myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
    }
    catch (Exception exc)
    {
        try
        {
            MessageBox.Show("Fatal Non-UI Error",
                "Fatal Non-UI Error. Could not write the error to the event log. Reason: "
                + exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
        finally
        {
            Application.Exit();
        }
    }
}

// Creates the error message and displays it.
private static DialogResult ShowThreadExceptionDialog(string title, Exception e)
{
    string errorMsg = "An application 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, title, MessageBoxButtons.AbortRetryIgnore,
        MessageBoxIcon.Stop);
}
Private newThread As Thread = Nothing

' Starts the application. 
<SecurityPermission(SecurityAction.Demand, Flags:=SecurityPermissionFlag.ControlAppDomain)> _
Public Shared Sub Main()
    ' Add the event handler for handling UI thread exceptions to the event.
    AddHandler Application.ThreadException, AddressOf ErrorHandlerForm.Form1_UIThreadException

    ' Set the unhandled exception mode to force all Windows Forms errors to go through
    ' our handler.
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)

    ' Add the event handler for handling non-UI thread exceptions to the event. 
    AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException

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


' Programs the button to throw an 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

' Start a new thread, separate from Windows Forms, that will throw an exception.
Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button2.Click
    Dim newThreadStart As New ThreadStart(AddressOf newThread_Execute)
    newThread = New Thread(newThreadStart)
    newThread.Start()
End Sub


' The thread we start up to demonstrate non-UI exception handling. 
Sub newThread_Execute()
    Throw New Exception("The method or operation is not implemented.")
End Sub


' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution.
Private Shared Sub Form1_UIThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
    Dim result As System.Windows.Forms.DialogResult = _
        System.Windows.Forms.DialogResult.Cancel
    Try
        result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception)
    Catch
        Try
            MessageBox.Show("Fatal Windows Forms Error", _
                "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
        Finally
            Application.Exit()
        End Try
    End Try

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

' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution.
' NOTE: This exception cannot be kept from terminating the application - it can only 
' log the event, and inform the user about it. 
Private Shared Sub CurrentDomain_UnhandledException(ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs)
    Try
        Dim ex As Exception = CType(e.ExceptionObject, Exception)
        Dim errorMsg As String = "An application error occurred. Please contact the adminstrator " & _
            "with the following information:" & ControlChars.Lf & ControlChars.Lf

        ' Since we can't prevent the app from terminating, log this to the event log.
        If (Not EventLog.SourceExists("ThreadException")) Then
            EventLog.CreateEventSource("ThreadException", "Application")
        End If

        ' Create an EventLog instance and assign its source.
        Dim myLog As New EventLog()
        myLog.Source = "ThreadException"
        myLog.WriteEntry((errorMsg + ex.Message & ControlChars.Lf & ControlChars.Lf & _
            "Stack Trace:" & ControlChars.Lf & ex.StackTrace))
    Catch exc As Exception
        Try
            MessageBox.Show("Fatal Non-UI Error", "Fatal Non-UI Error. Could not write the error to the event log. " & _
                "Reason: " & exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop)
        Finally
            Application.Exit()
        End Try
    End Try
End Sub


' Creates the error message and displays it.
Private Shared Function ShowThreadExceptionDialog(ByVal title As String, ByVal e As Exception) As DialogResult
    Dim errorMsg As String = "An application error occurred. Please contact the adminstrator " & _
 "with the following information:" & ControlChars.Lf & ControlChars.Lf
    errorMsg = errorMsg & e.Message & ControlChars.Lf & _
 ControlChars.Lf & "Stack Trace:" & ControlChars.Lf & e.StackTrace

    Return MessageBox.Show(errorMsg, title, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
End Function

설명

이 이벤트를 통해 Windows Forms 응용 프로그램은 Windows Forms 스레드에서 발생 하는 처리 되지 않은 예외를 처리할 수 있습니다.This event allows your Windows Forms application to handle otherwise unhandled exceptions that occur in Windows Forms threads. 이벤트에 이벤트 처리기를 연결 하 여 ThreadException 이러한 예외를 처리 하면 응용 프로그램이 알 수 없는 상태로 유지 됩니다.Attach your event handler to the ThreadException event to deal with these exceptions, which will leave your application in an unknown state. 가능 하면 구조화 된 예외 처리 블록에서 예외를 처리 해야 합니다.Where possible, exceptions should be handled by a structured exception handling block.

을 설정 하 여이 콜백이 처리 되지 않은 Windows Forms 스레드 예외에 사용 되는지 여부를 변경할 수 있습니다 SetUnhandledExceptionMode .You can change whether this callback is used for unhandled Windows Forms thread exceptions by setting SetUnhandledExceptionMode. Windows Forms에서 만들어지고 소유 하지 않은 스레드에서 발생 하는 예외를 catch 하려면 UnhandledException 이벤트 처리기를 사용 합니다.To catch exceptions that occur in threads not created and owned by Windows Forms, use the UnhandledException event handler.

참고

이 이벤트의 활성화가 누락 되지 않도록 하려면를 호출 하기 전에 처리기를 연결 해야 Application.Run 합니다.To guarantee that no activations of this event are missed, you must attach a handler before you call Application.Run.

참고

이 이벤트에는 처리기를 하나만 연결할 수 있습니다.Only one handler can be attached to this event. 여러 처리기를 추가 하는 경우 가장 최근에 추가 된 처리기만 처리 되지 않은 예외에서 호출 됩니다.If multiple handlers are added, only the most recently added handler will be called on an unhandled exception.

주의

정적 이벤트 이기 때문에 애플리케이션 삭제 되거나 메모리 누수가 발생 하는 경우 이벤트 처리기를 분리 해야 합니다.Because this is a static event, you must detach your event handlers when your application is disposed, or memory leaks will result.

적용 대상