AppDomain.UnhandledException Händelse

Definition

Inträffar när ett undantag inte fångas.

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

Händelsetyp

Implementeringar

Attribut

Exempel

I följande exempel visas händelsen UnhandledException . Den definierar en händelsehanterare, MyHandler, som anropas när ett ohanterat undantag genereras i standardprogramdomänen. Sedan utlöser den två undantag. Den första hanteras av ett try/catch-block . Den andra är ohanterad och anropar rutinen MyHandle innan programmet avslutas.

// 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;

public class Example
{
   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()
open System
open System.Security.Permissions

let myHandler _ (args: UnhandledExceptionEventArgs) =
    let e = args.ExceptionObject :?> Exception
    printfn $"MyHandler caught : {e.Message}"
    printfn $"Runtime terminating: {args.IsTerminating}"

[<EntryPoint>]
let main _ =
    let currentDomain = AppDomain.CurrentDomain
    currentDomain.UnhandledException.AddHandler(UnhandledExceptionEventHandler myHandler)

    try
        failwith "1"
    with e ->
        printfn $"Catch clause caught : {e.Message} \n"

    failwith "2"

// 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()

Kommentarer

Hanterare kan anropas flera gånger om undantag utlöses från olika trådar.

Händelsen UnhandledException innehåller ett meddelande om undantag som inte har genererats. Det gör att programmet kan logga information om undantaget innan systemstandardhanteraren rapporterar undantaget till användaren och avslutar programmet. Om det finns tillräckligt med information om programmets tillstånd kan andra åtgärder vidtas, till exempel att spara programdata för senare återställning. Försiktighet rekommenderas eftersom programdata kan skadas när undantag inte hanteras. Hanteraren kommer också att köras medan lås hålls kvar när undantaget utlöstes, så var noga med att undvika att vänta på andra resurser som kan leda till dödlägen.

Den här händelsen kan hanteras i alla programdomäner. Händelsen genereras dock inte nödvändigtvis i programdomänen där undantaget inträffade. Ett undantag är ohanterat endast om hela stacken för tråden har avvecklats utan att hitta en tillämplig undantagshanterare, så det första stället där händelsen kan aktiveras är i applikationsdomänen där tråden startade.

Om händelsen UnhandledException hanteras i standardprogramdomänen aktiveras den där för alla ohanterade undantag i alla trådar, oavsett vilken programdomän tråden startade i. Om tråden startade i en programdomän som har en händelsehanterare för UnhandledExceptiongenereras händelsen i programdomänen. Om programdomänen inte är standardprogramdomänen och det också finns en händelsehanterare i standardprogramdomänen, genereras händelsen i båda programdomänerna.

Anta till exempel att en tråd startar i programdomänen "AD1", anropar en metod i programdomänen "AD2" och därifrån anropar en metod i programdomänen "AD3", där den genererar ett undantag. Den första programdomänen UnhandledException där händelsen kan aktiveras är "AD1". Om programdomänen inte är standardprogramdomänen kan händelsen även aktiveras i standardprogramdomänen.

Note

Common Language Runtime (CLR) pausar trådavbrott medan händelsehanterare för UnhandledException-händelsen körs.

Om händelsehanteraren har ett ReliabilityContractAttribute attribut med lämpliga flaggor behandlas händelsehanteraren som en begränsad körningsregion.

Den här händelsen utlöses inte för undantag som skadar processens tillstånd, till exempel stackspill eller åtkomstöverträdelser, såvida inte händelsehanteraren är säkerhetskritisk och har HandleProcessCorruptedStateExceptionsAttribute attributet .

Om du vill registrera en händelsehanterare för den här händelsen måste du ha de nödvändiga behörigheterna, annars kastas en SecurityException.

Mer information om hur du hanterar händelser finns i Hantera och höja händelser.

Andra händelser för ohanterade undantag

För vissa programmodeller UnhandledException kan händelsen föregripas av andra händelser om det ohanterade undantaget inträffar i huvudprogramtråden.

I program som använder Windows Forms leder ohanterade undantag i huvudprogramtråden Application.ThreadException till att händelsen aktiveras. Om den här händelsen hanteras är standardbeteendet att det ohanterade undantaget inte avslutar programmet, även om programmet lämnas i ett okänt tillstånd. I så fall genereras UnhandledException inte händelsen. Det här beteendet kan ändras med hjälp av programkonfigurationsfilen eller med hjälp Application.SetUnhandledExceptionMode av metoden för att ändra läget till UnhandledExceptionMode.ThrowException innan ThreadException händelsehanteraren ansluts. Detta gäller endast för huvudprogramtråden. Händelsen UnhandledException aktiveras för ohanterade undantag som genereras i andra trådar.

Visual Basic-programramverket tillhandahåller en annan händelse för ohanterade undantag i huvudprogramtråden—händelsen WindowsFormsApplicationBase.UnhandledException. Den här händelsen har ett objekt för händelseargument med samma namn som det händelseargumentobjekt som används av AppDomain.UnhandledException, men med olika egenskaper. I synnerhet har det här händelseargumentobjektet en ExitApplication egenskap som gör att programmet kan fortsätta köras, ignorera det ohanterade undantaget (och lämna programmet i ett okänt tillstånd). I så fall genereras AppDomain.UnhandledException inte händelsen.

Gäller för