UnhandledExceptionEventArgs.ExceptionObject Свойство

Определение

Возвращает необработанный объект исключения.

public:
 property System::Object ^ ExceptionObject { System::Object ^ get(); };
public object ExceptionObject { get; }
member this.ExceptionObject : obj
Public ReadOnly Property ExceptionObject As Object

Значение свойства

Необработанный объект исключения.

Примеры

В следующем примере показано UnhandledException событие . Он определяет обработчик событий , MyHandlerкоторый вызывается при возникновении необработанного исключения в домене приложения по умолчанию. Затем он создает два исключения. Первый обрабатывается блоком try/catch . Второй является необработанным и вызывает подпрограмму MyHandle перед завершением работы приложения.

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

Комментарии

Это свойство возвращает объект типа Object , а не объект, производный от Exception. Хотя спецификация COMMON требует, чтобы все типы исключений были производными от Exception, методы могут создавать исключения с объектами, не производными от Exception. Для работы с этим исключением можно выполнить следующие действия.

  • Примените RuntimeCompatibilityAttribute атрибут со значением trueRuntimeCompatibilityAttribute.WrapNonExceptionThrows к сборке, содержащей обработчик событий. Это создает оболочку для всех исключений, не производных Exception от класса в объекте RuntimeWrappedException . Затем можно безопасно привести (в C#) или преобразовать (в Visual Basic) объект, возвращенный этим свойством Exception , в объект и получить исходный объект исключения из RuntimeWrappedException.WrappedException свойства . Обратите внимание, что некоторые компиляторы, такие как компиляторы C# и Visual Basic, автоматически применяют этот атрибут.

  • Приведите объект, возвращенный этим свойством, к объекту Exception .

Применяется к

См. также раздел