简体   繁体   中英

Efficient way to handle COM related errors (C++)

Efficient way to handle COM related errors in . 处理COM相关错误的有效方法。

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 :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM