Exception.HResult 屬性

定義

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。

C#
public int HResult { get; protected set; }
C#
public int HResult { get; set; }
C#
protected int HResult { get; set; }

屬性值

HRESULT 值。

範例

下列程式碼範例會定義衍生 Exception 類別,將 HResult 屬性設定為其建構函式中的自訂值。

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

備註

HRESULT 是一個 32 位元的值,分成三個不同的欄位:嚴重性代碼、設備碼和錯誤碼。 嚴重性代碼指出傳回值是代表資訊、警告還是錯誤。 設備碼指出系統要對錯誤負責的區域。 錯誤碼是指派來代表例外狀況的唯一號碼。 每個例外狀況都會對應至不同的 HRESULT。 當 Managed 程式碼擲回例外狀況時,執行時間會將 HRESULT 傳遞至 COM 用戶端。 當 Unmanaged 程式碼傳回錯誤時,HRESULT 會轉換成例外狀況,然後由執行時間擲回。 如需 HRESULT 值及其對應.NET Framework例外狀況的相關資訊,請參閱如何:對應 HRESULT 和例外狀況。 如需您最常遇到的值清單,請參閱 Windows 檔中的 常見 HRESULT 值

從 .NET Framework 4.5 開始, HResult 屬性的 setter 會受到保護,而其 getter 則是公用的。 在舊版.NET Framework中,getter 和 setter 都會受到保護。

適用於

產品 版本
.NET Core 1.0, Core 1.1, 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 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱