tags:

views:

116

answers:

1

Efficient way to handle COM related errors in C++.

For instance:

 switch (HRESULT_CODE(hresult)) {
 case NOERROR:
          cout << "Object instantiated and "
    "pointer to interface IS8Simulation " 
    "obtained" << endl;
  break;
 //Specifed Class not registered
 case REGDB_E_CLASSNOTREG:
  cerr << "Specified Class not registered." << endl;
  exit (EXIT_FAILURE);
  break;
 case CLASS_E_NOAGGREGATION:
          cerr << "The Class does not support aggregation "
    "(or class object is remote)." << endl;
  exit (EXIT_FAILURE);
  break;
 //Interface not supported - exit with error
 case E_NOINTERFACE:
  cerr << "No such interface supported." << endl;
  exit (EXIT_FAILURE);
  break;
 case E_UNEXPECTED:
 default:
  cerr << "Catastrophic failure." << endl;
  exit (EXIT_FAILURE);
  break;
 }

Compared to, the former:

if (SUCCEEDED(hresult))
{
         cout << "The COM library was initialised"
   " successfully on this thread" << endl;
} else {
         cerr << "Fatal Error: COM library was not"
   " initialised" << endl;
 exit (EXIT_FAILURE);
}

Question:

  • Any other method more applicable?

Regards

+4  A: 

Use FormatMessage to get the error text -- it already knows how to look up the localized text for most HRESULTs and Win32 result codes.

Use the FAILED and SUCCEEDED macros to work out if something has worked or not.

exit takes 32-bit numbers. You can use an HRESULT as your process exit code:

HRESULT hr;
if (FAILED(hr = p->QueryInterface(...)))
{
    cerr << MessageFromHResult(hr); // left as an exercise for the reader
    exit(hr);
}
Roger Lipscombe
Great! Thanks Roger :)
Aaron
exit(HRESULT); ?
Aaron
Thanks Roger :) woooooooo!
Aaron