Exception.HResult Свойство

Определение

Возвращает или задает HRESULT — кодированное числовое значение, присвоенное определенному исключению.

public:  property int HResult {  public:
int get(); protected:
 void set(int value); };
public:
 property int HResult { int get(); void set(int value); };
protected:
 property int HResult { int get(); void set(int value); };
public int HResult { get; protected set; }
public int HResult { get; set; }
protected int HResult { get; set; }
member this.HResult : int with get, set
Public Property HResult As Integer
Protected Property HResult As Integer

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

Int32

Значение HRESULT.

Примеры

В следующем примере кода определяется производный Exception класс, который присваивает HResult свойству пользовательское значение в конструкторе.

// Example for the Exception::HResult property.
using namespace System;

namespace NDP_UE_CPP
{

   // Create the derived exception class.
   ref class SecondLevelException: public Exception
   {
   private:
      static int SecondLevelHResult = (int)0x81234567;

   public:

      // Set HResult for this exception, and include it in 
      // the exception message.
      SecondLevelException( String^ message, Exception^ inner )
         : Exception( String::Format( "(HRESULT:0x{1:X8}) {0}", message, SecondLevelHResult ), inner )
      {
         HResult = SecondLevelHResult;
      }

   };


   // This function forces a division by 0 and throws 
   // a second exception.
   void DivideBy0()
   {
      try
      {
         try
         {
            int zero = 0;
            int ecks = 1 / zero;
         }
         catch ( Exception^ ex ) 
         {
            throw gcnew SecondLevelException( "Forced a division by 0 and threw "
            "a second exception.",ex );
         }

      }
      catch ( Exception^ ex ) 
      {
         Console::WriteLine( ex->ToString() );
      }

   }

}

int main()
{
   NDP_UE_CPP::DivideBy0();
}

/*
This example of Exception::HResult generates the following output.

NDP_UE_CPP.SecondLevelException: (HRESULT:0x81234567) Forced a division by 0 an
d threw a second exception. ---> System.DivideByZeroException: Attempted to div
ide by zero.
   at NDP_UE_CPP.DivideBy0()
   --- End of inner exception stack trace ---
   at NDP_UE_CPP.DivideBy0()
*/
// Example for the Exception.HResult property.
using System;

namespace NDP_UE_CS
{
    // Create the derived exception class.
    class SecondLevelException : Exception
    {
        const int SecondLevelHResult = unchecked( (int)0x81234567 );

        // Set HResult for this exception, and include it in
        // the exception message.
        public SecondLevelException( string message, Exception inner ) :
            base( string.Format( "(HRESULT:0x{1:X8}) {0}",
                message, SecondLevelHResult ), inner )
        {
            HResult = SecondLevelHResult;
        }
    }

    class HResultDemo
    {
        public static void Main()
        {
            // This function forces a division by 0 and throws
            // a second exception.
            try
            {
                try
                {
                    int  zero = 0;
                    int  ecks = 1 / zero;
                }
                catch( Exception ex )
                {
                    throw new SecondLevelException(
                        "Forced a division by 0 and threw " +
                        "a second exception.", ex );
                }
            }
            catch( Exception ex )
            {
                Console.WriteLine( ex.ToString( ) );
            }
        }
    }
}

/*
This example of Exception.HResult generates the following output.

NDP_UE_CS.SecondLevelException: (HRESULT:0x81234567) Forced a division by 0 and
 threw a second exception. ---> System.DivideByZeroException: Attempted to divi
de by zero.
   at NDP_UE_CS.HResultDemo.Main()
   --- End of inner exception stack trace ---
   at NDP_UE_CS.HResultDemo.Main()
*/
// Example for the Exception.HResult property.
open System

let secondLevelHResult = 0x81234567

// Create the derived exception class.
// Set HResult for this exception, and include it in the exception message.
type SecondLevelException(message, inner) as this =
    inherit Exception($"(HRESULT:0x{secondLevelHResult:X8}) %s{message}", inner)
    do
        this.HResult <- secondLevelHResult

// The following forces a division by 0 and throws a second exception.
try
    try
        let zero = 0
        let ecks = 1 / zero
        ()
    with ex ->
        raise (SecondLevelException("Forced a division by 0 and threw a second exception.", ex) )
with ex ->
    printfn $"{ex}"

// This example of Exception.HResult generates the following output.
//
// NDP_UE_FS+SecondLevelException: (HRESULT:0x81234567) Forced a division by 0 and
//  threw a second exception. ---> System.DivideByZeroException: Attempted to divi
// de by zero.
//    at <StartupCode$fs>.$NDP_UE_FS.main@()
//    --- End of inner exception stack trace ---
//    at <StartupCode$fs>.$NDP_UE_FS.main@()
' Example for the Exception.HResult property.
Namespace NDP_UE_VB

    ' Create the derived exception class.
    Class SecondLevelException
        Inherits Exception

        Private Const SecondLevelHResult As Integer = &H81234567
       
        ' Set HResult for this exception, and include it in 
        ' the exception message.
        Public Sub New(message As String, inner As Exception)

            MyBase.New( String.Format( "(HRESULT:0x{1:X8}) {0}", _
                message, SecondLevelHResult ), inner )
            HResult = SecondLevelHResult
        End Sub
    End Class

    Module HResultDemo
       
        Sub Main()
            ' This function forces a division by 0 and throws 
            ' a second exception.
            Try
                Try
                    Dim zero As Integer = 0
                    Dim ecks As Integer = 1 \ zero

                Catch ex As Exception
                    Throw New SecondLevelException( _
                        "Forced a division by 0 and threw " & _
                        "a second exception.", ex )
                End Try
              
            Catch ex As Exception
                Console.WriteLine( ex.ToString( ) )
            End Try
        End Sub

    End Module ' HResultDemo
End Namespace ' NDP_UE_VB

' This example of Exception.HResult generates the following output.
' 
' NDP_UE_VB.SecondLevelException: (HRESULT:0x81234567) Forced a division by 0 a
' nd threw a second exception. ---> System.DivideByZeroException: Attempted to
' divide by zero.
'    at NDP_UE_VB.HResultDemo.Main()
'    --- End of inner exception stack trace ---
'    at NDP_UE_VB.HResultDemo.Main()

Комментарии

HRESULT — это 32-разрядное значение, разделенное на три разных поля: код серьезности, код объекта и код ошибки. Код серьезности указывает, представляет ли возвращенное значение сведения, предупреждение или ошибку. Код устройства определяет область системы, из-за которой возникла ошибка. Код ошибки ― это уникальный номер, представляющий исключение. Каждое исключение сопоставляется с отдельным HRESULT. Когда управляемый код создает исключение, среда выполнения передает HRESULT клиенту COM. Когда неуправляемый код возвращает ошибку, HRESULT преобразуется в исключение, которое затем вызывается средой выполнения. Сведения о значениях HRESULT и их соответствующих платформа .NET Framework исключениях см. в разделе "Практическое руководство. Сопоставление HRESULT и исключений". Общие значения HRESULT см. в Windows документации по списку наиболее вероятных значений.

Начиная с платформа .NET Framework 4.5 HResult метод задания свойства защищен, тогда как его метод получения является общедоступным. В предыдущих версиях платформа .NET Framework защита метода получения и задания.

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

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