AppDomain.UnhandledException 事件

定義

發生於未攔截到例外狀況時。

C#
public event UnhandledExceptionEventHandler? UnhandledException;
C#
public event UnhandledExceptionEventHandler UnhandledException;
C#
[add: System.Security.SecurityCritical]
[remove: System.Security.SecurityCritical]
public event UnhandledExceptionEventHandler UnhandledException;

事件類型

實作

屬性

範例

下列範例示範 UnhandledException 事件。 它會定義事件處理程式 MyHandler,每當默認應用程式域中擲回未處理的例外狀況時,就會叫用這個事件處理程式。 然後會擲回兩個例外狀況。 第一個是由 try/catch 區塊處理。 第二個未處理,並在應用程式終止之前叫 MyHandle 用例程。

C#
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()

備註

如需此 API 的詳細資訊,請參閱 UnhandledException 的補充 API 備註

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1