You need a reference table that maps each
COM HRESULT
to its managed exception counterpart. This
mapping will allow you to throw the correct managed exception in C#,
which will map to the expected COM HRESULT
in
unmanaged code.
Every managed exception maps to an HRESULT
. Table 5-2 lists the managed exception classes and their
equivalent HRESULT
values. Use this table to
determine what type of managed exception to use when throwing an
exception back to unmanaged code, as well as what type of exception
object to use when handling returned COM/COM+
HRESULT
values.
Table 5-2. Mappping .NET exceptions to HRESULTS
.NET exception class name |
HRESULT name (hex value of HRESULT) |
---|---|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
Handling exceptions generated by COM/COM+ components involves the following two steps:
Handle any specific exceptions that the .NET Common Language Runtime
maps the COM/COM+ HRESULT
s in which
you’re interested. The table in the Discussion
section lists the standard HRESULT
values returned
by COM/COM+ objects and the .NET exceptions classes to which they are
mapped.
Handle any user-defined exceptions that are unique to a specific
COM/COM+ component by trapping the COMException
exception. The COMException
class reflects
COM/COM+ HRESULT
s that have no mapping to managed
exceptions.
The following code fragment illustrates this handling of COM/COM+ exceptions:
try { CallCOMMethod( ); } catch (UnauthorizedAccessException uae) { // Handle COM/COM+ access exceptions here } catch (System.Runtime.InteropServices.COMException ce) { // Handle user-defined COM/COM+ exceptions here } catch (Exception e) { // Handle all other exceptions here }
See Recipe 5.9 for more information on
handling user-defined HRESULT
s.
See Recipe 5.9; see the “Error Raising and Handling Guidelines,” “HRESULTs and Exceptions,” and “Handling COM Interop Exceptions” topics in the MSDN documentation.