處理 COM Interop 例外狀況Handling COM Interop Exceptions

Managed 和 Unmanaged 程式碼可一起運作來處理例外狀況。Managed and unmanaged code can work together to handle exceptions. 如果方法在 Managed 程式碼擲回例外狀況,則 Common Language Runtime 可以傳遞 HRESULT 給 COM 物件。If a method throws an exception in managed code, the common language runtime can pass an HRESULT to a COM object. 如果在 Unmanaged 程式碼中的方法藉由傳回失敗 HRESULT 而失敗,則執行階段會擲回 Managed 程式碼可以攔截的例外狀況。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 Interop 對應至更特定的例外狀況。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. COMExceptionErrorCode 屬性包含 HRESULT 值。The ErrorCode property of the COMException contains the HRESULT value.

使用 IErrorInfoWorking with IErrorInfo

當錯誤從 COM 傳遞至 Managed 程式碼時,執行階段會填入錯誤資訊至例外狀況物件。When an error is passed from COM to managed code, the runtime populates the exception object with error information. 支援 IErrorInfo 且傳回 HRESULT 的 COM 物件會提供這項資訊給 Managed 程式碼例外狀況。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.

如果在 Unmanaged 程式碼中的方法失敗,則例外狀況可以傳遞至 Managed 程式碼區段。If a method fails in unmanaged code, an exception can be passed to a managed code segment. 本主題 HRESULT 和例外狀況包含一個表格,顯示 HRESULT 如何對應至執行階段例外狀況物件。The topic HRESULTS and Exceptions contains a table showing how HRESULTS map to runtime exception objects.

另請參閱See also