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。 当托管代码引发异常时,运行时会将 HRESULT 传递给 COM 客户端。 当非托管代码返回错误时,HRESULT 将转换为异常,然后由运行时引发。 有关 HRESULT 值及其相应的.NET Framework异常的信息,请参阅如何:映射 HRESULT 和异常。 有关最有可能遇到的值的列表,请参阅 Windows 文档中的 常见 HRESULT 值

从 .NET Framework 4.5 开始,HResult属性的资源库受保护,而其 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

另请参阅