AppDomain.UnhandledException AppDomain.UnhandledException AppDomain.UnhandledException AppDomain.UnhandledException Event

定义

当某个异常未被捕获时出现。Occurs when an exception is not caught.

public:
 virtual event UnhandledExceptionEventHandler ^ UnhandledException;
[add: System.Security.SecurityCritical]
[remove: System.Security.SecurityCritical]
public event UnhandledExceptionEventHandler UnhandledException;
member this.UnhandledException : UnhandledExceptionEventHandler 
Public Custom Event UnhandledException As UnhandledExceptionEventHandler 

实现

属性

示例

下面的示例演示了UnhandledException该事件。The following example demonstrates the UnhandledException event. 它定义了一个事件处理MyHandler程序,该事件处理程序在默认应用程序域中引发未经处理的异常时调用。It defines an event handler, MyHandler, that is invoked whenever an unhandled exception is thrown in the default application domain. 然后,它将引发两个异常。It then throws two exceptions. 第一个由try/catch块处理。The first is handled by a try/catch block. 第二个未处理并在MyHandle应用程序终止前调用例程。The second is unhandled and invokes the MyHandle routine before the application terminates.

// The example should be compiled with the /clr:pure compiler option.
using namespace System;
using namespace System::Security::Permissions;

public ref class Example
{


private:
   static void MyHandler(Object^ sender, UnhandledExceptionEventArgs^ args)
   {
      Exception^ e = dynamic_cast<Exception^>(args->ExceptionObject);
      Console::WriteLine( "MyHandler caught : {0}", e->Message );
      Console::WriteLine("Runtime terminating: {0}", args->IsTerminating);
   }
   
public: 
   [SecurityPermissionAttribute( SecurityAction::Demand, ControlAppDomain = true )]
   static void Main()
   {
      AppDomain^ currentDomain = AppDomain::CurrentDomain;
      currentDomain->UnhandledException += gcnew UnhandledExceptionEventHandler(Example::MyHandler);
      try
      {
         throw gcnew Exception("1");
      }
      catch (Exception^ e) 
      {
         Console::WriteLine( "Catch clause caught : {0}\n", e->Message );
      }

      throw gcnew Exception("2");
   }
};

void main()
{
   Example::Main();
}   
// The example displays the following output:
//       Catch clause caught : 1
//       
//       MyHandler caught : 2
//       Runtime terminating: True
//       
//       Unhandled Exception: System.Exception: 2
//          at Example.Main()
//          at mainCRTStartup(String[] arguments)
using System;
using System.Security.Permissions;

public class Example 
{
   [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
   public static void Main()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
      
      try {
         throw new Exception("1");
      } catch (Exception e) {
         Console.WriteLine("Catch clause caught : {0} \n", e.Message);
      }

      throw new Exception("2");
   }
   
   static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
   {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
   }
}
// The example displays the following output:
//       Catch clause caught : 1
//       
//       MyHandler caught : 2
//       Runtime terminating: True
//       
//       Unhandled Exception: System.Exception: 2
//          at Example.Main()  
Module Example
   Sub Main()
      Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      AddHandler currentDomain.UnhandledException, AddressOf MyHandler
      
      Try
         Throw New Exception("1")
      Catch e As Exception
         Console.WriteLine("Catch clause caught : " + e.Message)
         Console.WriteLine()
      End Try
      
      Throw New Exception("2")
   End Sub
   
   Sub MyHandler(sender As Object, args As UnhandledExceptionEventArgs)
      Dim e As Exception = DirectCast(args.ExceptionObject, Exception)
      Console.WriteLine("MyHandler caught : " + e.Message)
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating)
   End Sub
End Module
' The example displays the following output:
'       Catch clause caught : 1
'       
'       MyHandler caught : 2
'       Runtime terminating: True
'       
'       Unhandled Exception: System.Exception: 2
'          at Example.Main()

注解

此事件提供未捕获的异常的通知。This event provides notification of uncaught exceptions. 它允许应用程序在系统默认处理程序向用户报告异常并终止应用程序之前记录有关异常的信息。It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. 如果提供了有关应用程序状态的足够信息,则可以执行其他操作,例如保存程序数据以便以后恢复。If sufficient information about the state of the application is available, other actions may be undertaken - such as saving program data for later recovery. 建议注意,因为在未处理异常时,程序数据可能会损坏。Caution is advised, because program data can become corrupted when exceptions are not handled.

备注

在 .NET Framework 版本1.0 和1.1 中,将在引发此事件之前向用户报告应用程序终止和调试选项,而不是在之后发出。In the .NET Framework versions 1.0 and 1.1, application termination and debugging options are reported to the user before this event is raised, rather than after.

可以在任何应用程序域中处理此事件。This event can be handled in any application domain. 但是,在发生异常的应用程序域中不一定会引发该事件。However, the event is not necessarily raised in the application domain where the exception occurred. 仅当在未查找适用的异常处理程序的情况下展开了线程的整个堆栈后,才会处理异常,因此可以引发事件的第一个位置是该线程源自的应用程序域。An exception is unhandled only if the entire stack for the thread has been unwound without finding an applicable exception handler, so the first place the event can be raised is in the application domain where the thread originated.

备注

在 .NET Framework 版本1.0 和1.1 中,此事件仅发生在启动应用程序时由系统创建的默认应用程序域中。In the .NET Framework versions 1.0 and 1.1, this event occurs only for the default application domain that is created by the system when an application is started. 如果应用程序创建了其他应用程序域,则在那些应用程序域中为此事件指定委托不起作用。If an application creates additional application domains, specifying a delegate for this event in those applications domains has no effect.

UnhandledException如果事件是在默认应用程序域中处理的,无论线程在哪个应用程序域中启动,都将为任何线程中的任何未经处理的异常引发此事件。If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. 如果该线程是在具有事件处理UnhandledException程序的应用程序域中启动的,则该事件会在该应用程序域中引发。If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. 如果该应用程序域不是默认应用程序域,并且在默认应用程序域中也有一个事件处理程序,则在这两个应用程序域中都会引发该事件。If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.

例如,假设某个线程在应用程序域 "AD1" 中启动,调用应用程序域 "AD2" 中的方法,并在其中调用应用程序域 "AD3" 中的方法,该方法将引发异常。For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. 可在其中UnhandledException引发事件的第一个应用程序域为 "AD1"。The first application domain in which the UnhandledException event can be raised is "AD1". 如果该应用程序域不是默认应用程序域,则还可以在默认应用程序域中引发该事件。If that application domain is not the default application domain, the event can also be raised in the default application domain.

备注

UnhandledException事件的事件处理程序正在执行时,公共语言运行时将挂起线程中止。The common language runtime suspends thread aborts while event handlers for the UnhandledException event are executing.

如果事件处理程序有一个ReliabilityContractAttribute具有相应标志的属性,则该事件处理程序将被视为受约束的执行区域。If the event handler has a ReliabilityContractAttribute attribute with the appropriate flags, the event handler is treated as a constrained execution region.

从开始HandleProcessCorruptedStateExceptionsAttribute ,对于损坏进程状态(如堆栈溢出或访问冲突)的异常,不会引发此事件,除非事件处理程序是安全关键的并且具有属性。 .NET Framework 4.NET Framework 4Starting with the .NET Framework 4.NET Framework 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.

在 .NET Framework 版本1.0 和1.1 中,在主应用程序线程之外的其他线程中发生的未经处理的异常将由运行时捕获,因此不会导致应用程序终止。In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. 因此, UnhandledException可以在应用程序终止的情况下引发事件。Thus, it is possible for the UnhandledException event to be raised without the application terminating. 从 .NET Framework 版本2.0 开始,已删除子线程中未经处理的异常的此项支撑,因为此类无提示故障的累积影响包括性能下降、损坏的数据和锁定,所有这些操作都难以debug.exe.Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug. 有关详细信息,包括运行时未终止的事例的列表,请参阅托管线程中的异常For more information, including a list of cases in which the runtime does not terminate, see Exceptions in Managed Threads.

若要为此事件注册事件处理程序,你必须具有所需的权限, SecurityException否则将引发。To register an event handler for this event, you must have the required permissions, or a SecurityException is thrown.

有关处理事件的详细信息, 请参阅处理和引发事件For more information about handling events, see Handling and Raising Events.

未经处理的异常的其他事件Other Events for Unhandled Exceptions

对于某些应用程序模型, UnhandledException如果主应用程序线程中出现未经处理的异常,则事件可能会被其他事件抢占。For certain application models, the UnhandledException event can be preempted by other events if the unhandled exception occurs in the main application thread.

在使用 Windows 窗体的应用程序中,主应用程序线程中的未Application.ThreadException处理异常将导致引发事件。In applications that use Windows Forms, unhandled exceptions in the main application thread cause the Application.ThreadException event to be raised. 如果处理此事件,则默认行为是未经处理的异常不会终止应用程序,但应用程序仍处于未知状态。If this event is handled, the default behavior is that the unhandled exception does not terminate the application, although the application is left in an unknown state. 在这种情况下UnhandledException ,不会引发事件。In that case, the UnhandledException event is not raised. 此行为可以通过使用应用程序配置文件进行更改,也可以通过使用Application.SetUnhandledExceptionMode方法在将ThreadException事件处理程序UnhandledExceptionMode.ThrowException挂钩之前更改模式。This behavior can be changed by using the application configuration file, or by using the Application.SetUnhandledExceptionMode method to change the mode to UnhandledExceptionMode.ThrowException before the ThreadException event handler is hooked up. 这仅适用于主应用程序线程。This applies only to the main application thread. 对于其他线程中引发的未经处理的异常,会引发事件。UnhandledExceptionThe UnhandledException event is raised for unhandled exceptions thrown in other threads.

从 Microsoft Visual Studio 2005 开始,Visual Basic 应用程序框架为主应用程序线程中的未处理异常提供另一个事件。Starting with Microsoft Visual Studio 2005, the Visual Basic application framework provides another event for unhandled exceptions in the main application thread. 请参阅WindowsFormsApplicationBase.UnhandledException事件。See the WindowsFormsApplicationBase.UnhandledException event. 此事件有一个事件参数对象,其名称与使用AppDomain.UnhandledException的事件参数对象同名,但具有不同的属性。This event has an event arguments object with the same name as the event arguments object used by AppDomain.UnhandledException, but with different properties. 特别是ExitApplication ,此事件参数对象具有属性,该属性允许应用程序继续运行,忽略未经处理的异常(并使应用程序处于未知状态)。In particular, this event arguments object has an ExitApplication property that allows the application to continue running, ignoring the unhandled exception (and leaving the application in an unknown state). 在这种情况下AppDomain.UnhandledException ,不会引发事件。In that case, the AppDomain.UnhandledException event is not raised.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

适用于