处理 COM 互操作异常Handling COM Interop Exceptions

托管和非托管代码可协同工作来处理异常。Managed and unmanaged code can work together to handle exceptions. 如果方法在托管代码中引发异常,公共语言运行时可将 HRESULT 传递至 COM 对象。If a method throws an exception in managed code, the common language runtime can pass an HRESULT to a COM object. 如果方法因返回失败 HRESULT 而在非托管代码中失败,运行时会引发可由托管代码捕获的异常。If a method fails in unmanaged code by returning a failure HRESULT, the runtime throws an exception that can be caught by managed code.

运行时自动将 HRESULT 从 COM 互操作映射到更具体的异常。The runtime automatically maps the HRESULT from COM interop to more specific exceptions. 例如,E_ACCESSDENIED 成为 UnauthorizedAccessException、E_OUTOFMEMORY 成为 OutOfMemoryException,依次类推。For example, E_ACCESSDENIED becomes UnauthorizedAccessException, E_OUTOFMEMORY becomes OutOfMemoryException, and so on.

如果 HRESULT 为自定义结果或运行时不知道它,运行时会将泛型 COMException 传递到客户端。If the HRESULT is a custom result or if it is unknown to the runtime, the runtime passes a generic COMException to the client. COMException 的 ErrorCode 属性包含 HRESULT 值。The ErrorCode property of the COMException contains the HRESULT value.

处理 IErrorInfoWorking with IErrorInfo

当错误从 COM 传递至托管代码时,运行时会将错误信息填充至异常对象。When an error is passed from COM to managed code, the runtime populates the exception object with error information. 支持 IErrorInfo 并返回 HRESULT 的 COM 对象将向托管代码异常提供此信息。COM objects that support IErrorInfo and return HRESULTS provide this information to managed code exceptions. 例如,运行时将“说明”从 COM 错误映射至异常的 Message 属性。For example, the runtime maps the Description from the COM error to the exception's Message property. 如果 HRESULT 未提供任何其他错误信息,运行时将对很多异常的属性填充默认值。If the HRESULT provides no additional error information, the runtime fills many of the exception's properties with default values.

如果方法在非托管代码中失败,则异常可以传递至托管代码段中。If a method fails in unmanaged code, an exception can be passed to a managed code segment. 主题 HRESULTS 和异常中的表展示了如何将 HRESULTS 映射到运行时异常对象。The topic HRESULTS and Exceptions contains a table showing how HRESULTS map to runtime exception objects.

另请参阅See also