处理COM相关错误的有效方法(C ++)

时间:2009-01-14 21:17:33

标签: c++ com

C ++中处理COM相关错误的有效方法

例如:

 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;
 }

相比:

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);
}

问题:

  • 更适用的其他任何方法?

此致

1 个答案:

答案 0 :(得分:4)

使用FormatMessage获取错误文本 - 它已经知道如何查找大多数HRESULT和Win32结果代码的本地化文本。

使用FAILEDSUCCEEDED宏来判断某些内容是否有效。

exit需要32位数字。您可以使用HRESULT作为流程退出代码:

HRESULT hr;
if (FAILED(hr = p->QueryInterface(...)))
{
    cerr << MessageFromHResult(hr); // left as an exercise for the reader
    exit(hr);
}