Friday, April 27, 2007

C# Catch COM exception on HRESULT

Quite straightforward, but had to look it up today. The HRESULT of a COM call in C# can be used to catch errors. If the COM component throws an error, it can be used like:


uint const HRESULT_ERROR = 0x80000000;
try
{
  CallCom();
}
catch (COMException comEx)
{
  if (comEx.ErrorCode == unchecked((int)HRESULT_ERROR))
  {
    DoSomething();
  }
}


Edit: Okay, made an mistake with this. HRESULT is an unsigned integer, so comparing it with an integer is not a good idea. We need to cast it unchecked to an integer.

No comments: