UnhandledExceptionMode UnhandledExceptionMode UnhandledExceptionMode UnhandledExceptionMode Enum

정의

Windows Forms 애플리케이션이 처리되지 않은 예외를 보내야 하는 위치를 정의합니다.Defines where a Windows Forms application should send unhandled exceptions.

public enum class UnhandledExceptionMode
public enum UnhandledExceptionMode
type UnhandledExceptionMode = 
Public Enum UnhandledExceptionMode
상속
UnhandledExceptionModeUnhandledExceptionModeUnhandledExceptionModeUnhandledExceptionMode

필드

Automatic Automatic Automatic Automatic 0

애플리케이션의 구성 파일에서 따로 지정하지 않는 한 모든 예외를 ThreadException 처리기로 보냅니다.Route all exceptions to the ThreadException handler, unless the application's configuration file specifies otherwise.

CatchException CatchException CatchException CatchException 2

예외를 항상 ThreadException 처리기로 보냅니다.Always route exceptions to the ThreadException handler. 애플리케이션 구성 파일을 무시합니다.Ignore the application configuration file.

ThrowException ThrowException ThrowException ThrowException 1

예외를 ThreadException 처리기로 보내지 않습니다.Never route exceptions to the ThreadException handler. 애플리케이션 구성 파일을 무시합니다.Ignore the application configuration file.

예제

다음 코드 예제에서는 Windows Forms 스레드와 다른 스레드에서 발생 하는 오류 발생 하는 두 오류 모두에 대 한 이벤트 처리기를 설정 합니다.The following code example sets event handlers for both errors that occur on Windows Forms threads and errors that occur on other threads. 설정 SetUnhandledExceptionMode 모든 오류는 애플리케이션의 사용자 구성 파일의 설정에 관계 없이 애플리케이션에서 처리할 수 있도록 합니다.It sets SetUnhandledExceptionMode so that all errors are handled by the application, regardless of the settings in the application's user configuration file. 사용 된 ThreadException 이전의 대 한 이벤트 및 UnhandledException 후자에 대 한 이벤트.It uses the ThreadException event for the former, and the UnhandledException event for the latter. 이후 UnhandledException 애플리케이션을 막을 수 없습니다 종료에서 예제 오류를 기록 하기만 종료 전에 시스템 이벤트 로그에에서 있습니다.Since UnhandledException cannot prevent an application from terminating, the example simply logs the error in the system Event Log prior to termination.

이 샘플에서는 두 개의 정의 했다고 가정 Button 컨트롤 button1 하 고 button2의 프로그램 Form 클래스입니다.This sample 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

설명

이 열거형을 사용 하 여 SetUnhandledExceptionMode입니다.This enumeration is used by SetUnhandledExceptionMode.

참고

.NET framework 버전 2.0에서 호출 스택으로 전파를 처리 되지 않은 예외를 허용 하도록 공용 언어 런타임 동작을 변경 합니다.In the .NET Framework version 2.0, the common language runtime behavior changed to allow unhandled exceptions to propagate up the call stack. 애플리케이션 구성 파일을 통해이 동작을 비활성화할 수 있습니다.This behavior can be disabled via the application configuration file. 자세한 내용은 관리되는 스레드의 예외를 참조하세요.For more information, see Exceptions in Managed Threads.

적용 대상