24.6 Handling HRESULT Errors You want to properly handle errors returned from a COM object. | Technique COM methods always return an HRESULT , which is a 32-bit integer containing bit fields denoting various attributes about the error. However, when you use an interop assembly to call the method within a .NET application, you don't have access to that HRESULT because the parameter marked with retval is the return value. To solve this problem, whenever a COM method returns an HRESULT whose severity bit is set to 1, the runtime throws an exception. The .NET Framework maps most defined HRESULT s to a corresponding exception class. As an example, create a new method in the COM object that simply returns the value E_NOTIMPL , which is an error specifying that the method is not implemented by the object. This error maps to the NotImplementedException class. Just as there are several different possible exceptions that .NET object can throw, a COM object may return one of several different errors, depending on the situation that caused the error to occur. Some are errors such as E_FAIL , E_POINTER , and E_OUTOFMEMORY . You should ensure that you also create a catch block for any extra exceptions by using the generic Exception class, as shown in the following code: // the following method will generate an exception if not handled try { commandObj.CurrentDirectory = "C:\"; } catch( NotImplementedException ex ) { MessageBox.Show( ex.TargetSite.Name + ": " + ex.Message ); } catch( Exception ex ) { MessageBox.Show( ex.Message ); } Comments HRESULT s were created as a way to perform error handling without requiring the use of exceptions. The reason this method was chosen is that COM is a language-neutral technology and, like .NET, simply provides a specification that all languages, which want to play in the same sandbox, must follow. This being the case, not all languages at that time supported exceptions, and if they did, the exception mechanics were different from those employed within Visual C++. |