O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.9. Handling User-Defined HRESULTs

Problem

A COM object can return a user-defined HRESULT or an HRESULT that has no mapping to a managed exception type. You wish to handle these returned HRESULTs in a more specific manner.

Solution

The following code fragment illustrates the handling of user-defined COM/COM+ exceptions:

try
{
    CallCOMMethod( );
}
catch (System.Runtime.InteropServices.COMException ce)
{
    switch ((uint)ce.ErrorCode)
    {
        case 0x80132000:
            // Handle this specific user-defined COM/COM+ exceptions here
            break;
        case 0x80132001:
            // Handle this specific user-defined COM/COM+ exceptions here
            break;
        default:
            // Handle any other specific user-defined COM/COM+ 
            // exceptions here
            break;
    }
}
catch (Exception e)
{
    // Handle all other exceptions here
}

Discussion

Handle any user-defined exceptions that are unique to a specific COM/COM+ component by trapping the COMException exception. This class reflects COM/COM+ HRESULTs that have no mapping to managed exceptions.

The COMException has a property, ErrorCode, in addition to those properties in the base Exception class. This property contains the HRESULT value that the COM/COM+ object returned. Another difference between COMException and Exception is that the InnerException property of a COMException object will always be null.

See Also

See the “Error Raising and Handling Guidelines” and “Handling COM Interop Exceptions” topics in the MSDN documentation.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required