如何:映射 HRESULT 和异常How to: Map HRESULTs and Exceptions

COM 方法通过返回 HRESULT 来报告错误;NET 方法通过引发异常来报告错误。COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. 运行时处理这两者之间的转换。The runtime handles the transition between the two. NET Framework 中的每个异常类都将映射到 HRESULT。Each exception class in the .NET Framework maps to an HRESULT.

用户定义的异常类可指定任何适用的 HRESULT。User-defined exception classes can specify whatever HRESULT is appropriate. 这些异常类可动态更改通过设置异常对象上的 HResult 字段生成异常时返回的 HRESULT。These exception classes can dynamically change the HRESULT to be returned when the exception is generated by setting the HResult field on the exception object. 异常的其他信息通过 IErrorInfo 接口提供给客户端,这是在非管理进程中的 NET 对象上实现的。Additional information about the exception is provided to the client through the IErrorInfo interface, which is implemented on the .NET object in the unmanaged process.

如果要创建扩展 System.Exception 的类,需要在构造时设置 HRESULT 字段。If you create a class that extends System.Exception, you must set the HRESULT field during construction. 否则,基类将分配 HRESULT 值。Otherwise, the base class assigns the HRESULT value. 可以通过提供异常的构造函数的值,将新的异常类映射到现有的 HRESULT。You can map new exception classes to an existing HRESULT by supplying the value in the exception's constructor.

请注意,如果线程上存在 IErrorInfo,运行时将忽略 HRESULTNote that the runtime will sometimes ignore an HRESULT in cases where there is an IErrorInfo present on the thread. 此行为可以发生在 HRESULTIErrorInfo 表示不同错误的事例中。This behavior can occur in cases where the HRESULT and the IErrorInfo do not represent the same error.

创建新的异常类并将其映射到 HRESULTTo create a new exception class and map it to an HRESULT

  1. 使用以下代码创建名为 NoAccessException 的新的异常类,并将其映射到 HRESULT E_ACCESSDENIEDUse the following code to create a new exception class called NoAccessException and map it to the HRESULT E_ACCESSDENIED.

    Class NoAccessException : public ApplicationException  
    {  
        NoAccessException () {  
        HResult = E_ACCESSDENIED;   
    }  
    }  
    CMyClass::MethodThatThrows  
    {  
    throw new NoAccessException();  
    }  
    

可能会遇到同时使用托管和非托管代码的程序(使用任何编程语言)。You might encounter a program (in any programming language) that uses both managed and unmanaged code at the same time. 例如,以下代码示例中的自定义封送处理程序使用 Marshal.ThrowExceptionForHR (int HResult) 方法,以使用特定 HRESULT 值引发异常。For example, the custom marshaler in the following code example uses the Marshal.ThrowExceptionForHR(int HResult) method to throw an exception with a specific HRESULT value. 此方法查找 HRESULT,并生成适当的异常类型。The method looks up the HRESULT and generates the appropriate exception type. 例如,以下代码片段中的 HRESULT 可生成 ArgumentException。For example, the HRESULT in the following code fragment generates ArgumentException.

CMyClass::MethodThatThrows  
{  
    Marshal.ThrowExceptionForHR(COR_E_ARGUMENT);  
}  

下表提供从每个 HRESULT 到其在 NET Framework 中的相似异常类的完整映射。The following table provides the complete mapping from each HRESULT to its comparable exception class in the .NET Framework.

HRESULTHRESULT .NET 异常.NET exception
MSEE_E_APPDOMAINUNLOADEDMSEE_E_APPDOMAINUNLOADED AppDomainUnloadedExceptionAppDomainUnloadedException
COR_E_APPLICATIONCOR_E_APPLICATION ApplicationExceptionApplicationException
COR_E_ARGUMENT 或 E_INVALIDARGCOR_E_ARGUMENT or E_INVALIDARG ArgumentExceptionArgumentException
COR_E_ARGUMENTOUTOFRANGECOR_E_ARGUMENTOUTOFRANGE ArgumentOutOfRangeExceptionArgumentOutOfRangeException
COR_E_ARITHMETIC 或 ERROR_ARITHMETIC_OVERFLOWCOR_E_ARITHMETIC or ERROR_ARITHMETIC_OVERFLOW ArithmeticExceptionArithmeticException
COR_E_ARRAYTYPEMISMATCHCOR_E_ARRAYTYPEMISMATCH ArrayTypeMismatchExceptionArrayTypeMismatchException
COR_E_BADIMAGEFORMAT 或 ERROR_BAD_FORMATCOR_E_BADIMAGEFORMAT or ERROR_BAD_FORMAT BadImageFormatExceptionBadImageFormatException
COR_E_COMEMULATE_ERRORCOR_E_COMEMULATE_ERROR COMEmulateExceptionCOMEmulateException
COR_E_CONTEXTMARSHALCOR_E_CONTEXTMARSHAL ContextMarshalExceptionContextMarshalException
COR_E_CORECOR_E_CORE CoreExceptionCoreException
NTE_FAILNTE_FAIL CryptographicExceptionCryptographicException
COR_E_DIRECTORYNOTFOUND 或 ERROR_PATH_NOT_FOUNDCOR_E_DIRECTORYNOTFOUND or ERROR_PATH_NOT_FOUND DirectoryNotFoundExceptionDirectoryNotFoundException
COR_E_DIVIDEBYZEROCOR_E_DIVIDEBYZERO DivideByZeroExceptionDivideByZeroException
COR_E_DUPLICATEWAITOBJECTCOR_E_DUPLICATEWAITOBJECT DuplicateWaitObjectExceptionDuplicateWaitObjectException
COR_E_ENDOFSTREAMCOR_E_ENDOFSTREAM EndOfStreamExceptionEndOfStreamException
COR_E_TYPELOADCOR_E_TYPELOAD EntryPointNotFoundExceptionEntryPointNotFoundException
COR_E_EXCEPTIONCOR_E_EXCEPTION ExceptionException
COR_E_EXECUTIONENGINECOR_E_EXECUTIONENGINE ExecutionEngineExceptionExecutionEngineException
COR_E_FIELDACCESSCOR_E_FIELDACCESS FieldAccessExceptionFieldAccessException
COR_E_FILENOTFOUND 或 ERROR_FILE_NOT_FOUNDCOR_E_FILENOTFOUND or ERROR_FILE_NOT_FOUND FileNotFoundExceptionFileNotFoundException
COR_E_FORMATCOR_E_FORMAT FormatExceptionFormatException
COR_E_INDEXOUTOFRANGECOR_E_INDEXOUTOFRANGE IndexOutOfRangeExceptionIndexOutOfRangeException
COR_E_INVALIDCAST 或 E_NOINTERFACECOR_E_INVALIDCAST or E_NOINTERFACE InvalidCastExceptionInvalidCastException
COR_E_INVALIDCOMOBJECTCOR_E_INVALIDCOMOBJECT InvalidComObjectExceptionInvalidComObjectException
COR_E_INVALIDFILTERCRITERIACOR_E_INVALIDFILTERCRITERIA InvalidFilterCriteriaExceptionInvalidFilterCriteriaException
COR_E_INVALIDOLEVARIANTTYPECOR_E_INVALIDOLEVARIANTTYPE InvalidOleVariantTypeExceptionInvalidOleVariantTypeException
COR_E_INVALIDOPERATIONCOR_E_INVALIDOPERATION InvalidOperationExceptionInvalidOperationException
COR_E_IOCOR_E_IO IOExceptionIOException
COR_E_MEMBERACCESSCOR_E_MEMBERACCESS AccessExceptionAccessException
COR_E_METHODACCESSCOR_E_METHODACCESS MethodAccessExceptionMethodAccessException
COR_E_MISSINGFIELDCOR_E_MISSINGFIELD MissingFieldExceptionMissingFieldException
COR_E_MISSINGMANIFESTRESOURCECOR_E_MISSINGMANIFESTRESOURCE MissingManifestResourceExceptionMissingManifestResourceException
COR_E_MISSINGMEMBERCOR_E_MISSINGMEMBER MissingMemberExceptionMissingMemberException
COR_E_MISSINGMETHODCOR_E_MISSINGMETHOD MissingMethodExceptionMissingMethodException
COR_E_MULTICASTNOTSUPPORTEDCOR_E_MULTICASTNOTSUPPORTED MulticastNotSupportedExceptionMulticastNotSupportedException
COR_E_NOTFINITENUMBERCOR_E_NOTFINITENUMBER NotFiniteNumberExceptionNotFiniteNumberException
E_NOTIMPLE_NOTIMPL NotImplementedExceptionNotImplementedException
COR_E_NOTSUPPORTEDCOR_E_NOTSUPPORTED NotSupportedExceptionNotSupportedException
COR_E_NULLREFERENCE orE_POINTERCOR_E_NULLREFERENCE orE_POINTER NullReferenceExceptionNullReferenceException
COR_E_OUTOFMEMORY 或COR_E_OUTOFMEMORY or

E_OUTOFMEMORYE_OUTOFMEMORY
OutOfMemoryExceptionOutOfMemoryException
COR_E_OVERFLOWCOR_E_OVERFLOW OverflowExceptionOverflowException
COR_E_PATHTOOLONG 或 ERROR_FILENAME_EXCED_RANGECOR_E_PATHTOOLONG or ERROR_FILENAME_EXCED_RANGE PathTooLongExceptionPathTooLongException
COR_E_RANKCOR_E_RANK RankExceptionRankException
COR_E_REFLECTIONTYPELOADCOR_E_REFLECTIONTYPELOAD ReflectionTypeLoadExceptionReflectionTypeLoadException
COR_E_REMOTINGCOR_E_REMOTING RemotingExceptionRemotingException
COR_E_SAFEARRAYTYPEMISMATCHCOR_E_SAFEARRAYTYPEMISMATCH SafeArrayTypeMismatchExceptionSafeArrayTypeMismatchException
COR_E_SECURITYCOR_E_SECURITY SecurityExceptionSecurityException
COR_E_SERIALIZATIONCOR_E_SERIALIZATION SerializationExceptionSerializationException
COR_E_STACKOVERFLOW orERROR_STACK_OVERFLOWCOR_E_STACKOVERFLOW orERROR_STACK_OVERFLOW StackOverflowExceptionStackOverflowException
COR_E_SYNCHRONIZATIONLOCKCOR_E_SYNCHRONIZATIONLOCK SynchronizationLockExceptionSynchronizationLockException
COR_E_SYSTEMCOR_E_SYSTEM SystemExceptionSystemException
COR_E_TARGETCOR_E_TARGET TargetExceptionTargetException
COR_E_TARGETINVOCATIONCOR_E_TARGETINVOCATION TargetInvocationExceptionTargetInvocationException
COR_E_TARGETPARAMCOUNTCOR_E_TARGETPARAMCOUNT TargetParameterCountExceptionTargetParameterCountException
COR_E_THREADABORTEDCOR_E_THREADABORTED ThreadAbortExceptionThreadAbortException
COR_E_THREADINTERRUPTEDCOR_E_THREADINTERRUPTED ThreadInterruptedExceptionThreadInterruptedException
COR_E_THREADSTATECOR_E_THREADSTATE ThreadStateExceptionThreadStateException
COR_E_THREADSTOPCOR_E_THREADSTOP ThreadStopExceptionThreadStopException
COR_E_TYPELOADCOR_E_TYPELOAD TypeLoadExceptionTypeLoadException
COR_E_TYPEINITIALIZATIONCOR_E_TYPEINITIALIZATION TypeInitializationExceptionTypeInitializationException
COR_E_VERIFICATIONCOR_E_VERIFICATION VerificationExceptionVerificationException
COR_E_WEAKREFERENCECOR_E_WEAKREFERENCE WeakReferenceExceptionWeakReferenceException
COR_E_VTABLECALLSNOTSUPPORTEDCOR_E_VTABLECALLSNOTSUPPORTED VTableCallsNotSupportedExceptionVTableCallsNotSupportedException
所有其他 HRESULTAll other HRESULTs COMExceptionCOMException

若要检索扩展的错误信息,托管客户端需要检查已生成的异常对象的字段。To retrieve extended error information, the managed client must examine the fields of the exception object that was generated. 若要异常对象提供有关错误的有用信息,COM 对象需要实现 IErrorInfo 接口。For the exception object to provide useful information about an error, the COM object must implement the IErrorInfo interface. 运行时使用由 IErrorInfo 提供的信息来初始化异常对象。The runtime uses the information provided by IErrorInfo to initialize the exception object.

如果 COM 对象不支持 IErrorInfo,运行时将使用默认值初始化异常对象。If the COM object does not support IErrorInfo, the runtime initializes an exception object with default values. 下表列出与异常对象关联的每个字段,并标识了当 COM 对象支持 IErrorInfo 时的默认信息源。The following table lists each field associated with an exception object and identifies the source of default information when the COM object supports IErrorInfo.

请注意,如果线程上存在 IErrorInfo,运行时将忽略 HRESULTNote that the runtime will sometimes ignore an HRESULT in cases where there is an IErrorInfo present on the thread. 此行为可以发生在 HRESULTIErrorInfo 表示不同错误的事例中。This behavior can occur in cases where the HRESULT and the IErrorInfo do not represent the same error.

异常字段Exception field 来自 COM 的信息源Source of Information from COM
ErrorCodeErrorCode 从调用返回的 HRESULT。HRESULT returned from call.
HelpLinkHelpLink 如果 IErrorInfo-> HelpContext 为非零值,字符串通过串联 IErrorInfo-> GetHelpFile 和“#”以及 IErrorInfo-> GetHelpContext 形成。If IErrorInfo->HelpContext is nonzero, the string is formed by concatenating IErrorInfo->GetHelpFile and "#" and IErrorInfo->GetHelpContext. 否则,字符串将从 IErrorInfo-> GetHelpFile 返回。Otherwise the string is returned from IErrorInfo->GetHelpFile.
InnerExceptionInnerException 通常为 null 引用(在 Visual Basic 中为 Nothing)。Always a null reference (Nothing in Visual Basic).
消息Message 从 IErrorInfo->GetDescription 返回的字符串。String returned from IErrorInfo->GetDescription.
Source 从 IErrorInfo->GetSource 返回的字符串。String returned from IErrorInfo->GetSource.
StackTraceStackTrace 堆栈跟踪。The stack trace.
TargetSiteTargetSite 返回出现故障的 HRESULT 的方法的名称。The name of the method that returned the failing HRESULT.

异常字段,如 Message、Source 和 StackTrace,不可用于 StackOverflowException。Exception fields, such as Message, Source, and StackTrace are not available for the StackOverflowException.

请参阅See also