Recipe 7.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 0x80042000:
// Handle specific user-defined COM/COM+ exception here.
break;
case 0x80042001:
// Handle specific user-defined COM/COM+ exception 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.
|